본문 바로가기
C#

[C#] 문자열에 특정 문자 개수 찾기

by Jcoder 2020. 11. 19.

1. LINQ 사용

public List<stringTaskFindText(string[] FindStrlst)

{

    // 1개 또는 목록이 없는 경우

    //if (FilelistCount <= 1) return null;

    var templist = GetFilesToStrList();

    IEnumerable<FileInfo> fileInfos = templist.Select(x => new FileInfo(x));

    

    HashSet<string> resultList = new HashSet<string>();

 

    foreach (var item in FindStrlst)

    {

        var queryMatchingFiles =

            from file in fileInfos

            where file.Extension.ToLower() == ".log"

            let fileText = GetFileText(file.FullName)

            where fileText.Contains(item)

            select file.FullName;

 

        foreach (string filename in queryMatchingFiles)

        {

            resultList.Add(filename);

        }

    }

    return new List<string>(resultList);

}

 

string GetFileText(string name)

{

    string fileContents = String.Empty;

 

    if (System.IO.File.Exists(name))

    {

        fileContents = System.IO.File.ReadAllText(name);

    }

    return fileContents;

}

2. 정규식 이용

using System.Text.RegularExpressions;

 

MatchCollection matches = Regex.Matches("hi, hi, everybody.", ",");

int cnt = matches.Count;

 

hi, hi, everybody.

문장에 , 가 2개 있으므로 cnt = 2 가 된다.

[출처] c# 문자열에 특정 문자가 몇개 있는지 알아내는 함수|작성자 바람

 

출처: <http://blog.naver.com/PostView.nhn?blogId=windlee5&logNo=20200009697>

 

 

'C#' 카테고리의 다른 글

[C#] BCL - DateTime Tick으로 시간차 계산  (0) 2020.11.28
[C#] Dispose 상속 및 재정의  (0) 2020.11.27
[C#] ini 파일 읽기/쓰기  (0) 2020.11.19
[C#] .Net core 3.1 인코딩 한글 지원  (0) 2020.11.19
[C#] FFMpeg.exe 사용 (m4a -> wav)  (0) 2020.11.19