본문 바로가기

코딩 공부/Unity C#

문자열 추출 Substring 사용 예제

<pyramid slot number>,<block letter>,<whether or not the block should be lit>

Example:

15,M,true

위와 같은 문자열에서 각각의 요소를 추출하여 변수에 저장한다

<pyramid slot number> - int

<block letter>- char

<whether or not the block should be lit> - bool

 

LastIndexOf 메서드 사용 불가, Substring 메세드를 사용하여 문제를 푼다

 

 

Substring
: 문자열의 특정 부분을 추출하여 새 문자열로 반환하는 메서드

1. Substring(int startIndex): 문자열의 startIndex 위치부터 끝까지의 부분 문자열을 반환
2. Substring(int startIndex, int length): 문자열의 startIndex 위치부터 지정된 length 길이만큼의 부분 문자열을 반환

 

 

문제 풀이

   static void Main(string[] args)
   {
       // 문자열 입력 및 변수 저장
       Console.Write("해당 항목을 입력해라" +
           "(피라미드 슬롯 번호,블록 번호, 블록점등번호): ");
       string str = Console.ReadLine();

       // 처음 등장하는 요소 추출하여 변수에 저장
       int indexNum1 = str.IndexOf(',');    // 첫번째 ,만 인식
       int slotNum = int.Parse(str.Substring(0, indexNum1));

       // 첫번째 콤마 위치까지 자르기
       string shortStr = str.Substring(indexNum1 + 1); 
       int indexNum2 = shortStr.IndexOf(",");

       // 블록 번호와 블록점등번호 추출 후 변수에 저장
       char blockNum = char.Parse(shortStr.Substring(0, indexNum2));
       bool blockLit = bool.Parse(shortStr.Substring(indexNum2 + 1));

       // 추출한 변수 출력
       Console.WriteLine(slotNum);
       Console.WriteLine(blockNum);
       Console.WriteLine(blockLit);
   }

- Parse를 사용하여 string 데이터 타입을 변환하였음

- IndexOf는 첫번째 ','만 인식한다. SubString으로 첫번째 콤마가 나오는 곳까지 자른다.

- 두번째 콤마의 위치를 찾은 후 나머지 요소를 추출하여 변수에 저장한다

 

해설과 비교

          // extract and print block letter
            char blockLetter = input[commaLocation + 1];
            Console.WriteLine("Block Letter: " + blockLetter);

- char은 문자 하나이므로 콤마 다음의 인덱스 부분을 가져와서 변수에 저장한다

            // extract and print whether or not the block should be lit
            string temp = input.Substring(commaLocation + 1);
            commaLocation = temp.IndexOf(',');
            bool lit = bool.Parse(temp.Substring(commaLocation + 1));
            Console.WriteLine("Block should be lit: " + lit);

- 콤마의 위치를 저장하는 변수와 사용자가 입력한 내용을 저장한 문자열 변수

새로 만들지 않고 기존 변수를 업데이트한다 (효율적 메모리 활용)