091
[C#] TQC+ 문제 CS_206 : 본문
728x90
🔍C#: CS_206 .
입력된 문자열이 주어진 문자열 리터럴 dreams에 몇 번 포함되어 있는지 출력하시오.
1. 문제 정답
using System;
namespace CS_206{
class CS_206{
const string dreams = "There are moments in life when you miss someone so much that " +
"you just want to pick them from your dreams and hug them for real! Dream what " +
"you want to dream;go where you want to go;be what you want to be,because you have " +
"only one life and one chance to do all the things you want to do";
static void Main(string[] args){
string input = Console.ReadLine();
int count = 0, startIndex = 0;
while((startIndex = dreams.IndexOf(input,startIndex)) != -1){
count++;
startIndex += input.Length;
}
Console.Write(count);
}
}
}
2. 정리
- IndexOf() 메서드는 문자열 객체에서 사용되는 메서드로, 특정 문자 또는 부분 문자열이 현재 문자열 내에 처음으로 나타나는 인덱스를 반환합니다. (현재 문자열).IndexOf(찾을문자열, 찾을 시작 위치(생략하면 0)) 처럼 사용해주며, 찾고자하는 문자열이 현재 문자열에 없는 경우 -1을 반환합니다.
string text = "Hello World Hello";
string searchString = "Hello";
int index1 = text.IndexOf(searchString); // index1은 0이 됩니다.
int index2 = text.IndexOf(searchString, 1); // index2는 12가 됩니다.
- 문자열의 길이를 셀 때 Length 속성을 사용합니다.
728x90
'Programming Language > C#' 카테고리의 다른 글
[C#] TQC+ 문제 CS_208 : (0) | 2025.05.13 |
---|---|
[C#] TQC+ 문제 CS_207 : (0) | 2025.05.13 |
[C#] TQC+ 문제 CS_205 : (0) | 2025.05.08 |
[C#] TQC+ 문제 CS_204 : (0) | 2025.05.08 |
[C#] TQC+ 문제 CS_203 : (0) | 2025.05.06 |