2012-06-19

C# Find number in String

문자열에서 숫자열을 찾아, 순서대로 List에 저장하는 클래스.

using System.Collections.Generic;

namespace automating_system_report
{
    class FindNumberInString
    {
        public List ListNumber=new List();
        public void FindNumber(string numStr)
        {
            int startIndex = 0;       // substring할 시작지점
            int lengthOfNumber = 0;   // substring할 길이
            int count=0;              // foreach에서 사용할 카운터
            bool bThisTurnIsNumeric;  // foreach에서 문자가 숫자인지 확인할 bool
            
            if (ListNumber != null)   // 함수가 이미 호출되어 리스트에 값이 있는 경우 clear
            { 
                ListNumber.Clear(); 
            }

            /// numStr += "/";  
            /// numStr에 "/"를 문자열 끝에 붙였던 이유는, 
            /// 문자열에서 숫자가 나오다 숫자가 아닌 문자가 나오면 그 순간 숫자열을 판단 하는데,
            /// 문자열 마지막이 숫자로 끝날 경우, List에 저장하지 못하고 foreach문을 끝내게된다..
            /// 
            /// 마지막에 if (bThisTurnIsNumeric == true && numStr.Length == (count + 1)) 로 대체함.
            foreach (char c in numStr)
            {
                bThisTurnIsNumeric = (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9');
                if (lengthOfNumber == 0)   //숫자가 아닌 경우, lengthOfNumber가 0이면 아직 문자열에서 숫자가 발견되지 않은 것, startIndex를 +1
                {
                    startIndex = count;
                }
                if (bThisTurnIsNumeric == true) //숫자를 찾은 경우, LengthOfNumber를 +1
                {
                    lengthOfNumber++;
                }

                if ((bThisTurnIsNumeric == false&&lengthOfNumber>0)                   //숫자열이 끝나고 문자가 시작되면 숫자열을 Substring할 준비가 된 것.
                    || (bThisTurnIsNumeric == true && numStr.Length == (count + 1)))  //문자열 마지막에 숫자열이 있을 경우, 다시 foreach를 실행하지 않을 것이므로 지금 저장
                {
                    ListNumber.Add(numStr.Substring(startIndex, lengthOfNumber));
                    lengthOfNumber = 0; // 문자열의 숫자부분 길이를 리셋
                }
                count++;
            }
        }
    }
}
/*          FindNumberInString fnfs = new FindNumberInString();
            fnfs.FindNumber("오늘 날짜는 2012년 06월 19일 17:29:00 ");
            int i = 0;
            foreach (string s in fnfs.ListNumber)
            {
                Trace.WriteLine(i.ToString() + ":" + s);
                i++;
            }

결과:
0:2012
1:06
2:19
3:17
4:29
5:00
*/
//

댓글 없음:

댓글 쓰기