문자열에서 특정 문자열이 있는지 찾는 방법
조회수 33619회
string 타입의 변수가 있을 때 그 안에 특정 문자열이 있는지 알아내려면 어떻게 하나요?
예를 들어
"Hello, It's me"
에서 "me"
를 찾으면 True
,
"????"
를 찾으면 False
같이요.
기왕이면 인덱스도 찾아줬으면 좋겠어요
1 답변
-
std::string::find를 써야 합니다.
원형:
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (char c, size_t pos = 0) const;
인자에 대한 설명:
str
: 찾고자 하는 문자열pos
:str
을 pos위치부터 찾기 시작합니다. ex)pos
=3이면 인덱스 3부터 찾아나감s
: 캐릭터형의 배열을 가리키는 포인터n
: 연속으로 일치해야 하는 최소 길이c
: 찾고자 하는 캐릭터(배열이 아니라 문자 하나)
return값:
- 첫 번째로 일치하는 문자의 위치를 return 해 줍니다.
- 일치하는 위치를 찾지 못한 경우
string::npos
를 return합니다.
예:
int main(){ string s1 = "hello! C wor"; string s2 = "world"; ssize_t pos; if ( (pos = s1.find(s2, 0, 3)) != std::string::npos) { std::cout << "found!" << '\n'; cout << pos << endl; } }
댓글 입력