✅ string.find()
문자열에서 원하는 문자열의 위치를 찾는다.
size_type find(const basic_string& str, size_type pos = 0) const;
size_type find(const CharT* s, size_type pos, size_type count) const;
size_type find(const CharT* s, size_type pos = 0) const;
size_type find(CharT ch, size_type pos = 0) const;
template <class T>
size_type find(const T& t, size_type pos = 0) const;
문자열을 찾는데
- 한문장 안에 MCD가 여러개 있을 수 있다.
- 따라서 찾기 시작할 위치를 알아야 하므로 첫번째 MCD를 찾고 두번째 부터는 전 위치의 다음 위치부터 탐색한다.
- 주의해야 할 점은 특정 위치에서 끝까지 탐색하면 중복되서 세어지므로 특정 위치에서 찾는 문장의 길이 만큼만 탐색해야 한다.
#include <iostream>
#include <string>
using namespace std;
string input[5];
int cnt;
int main(){
for(int i=0;i<5;i++){
cin >> input[i];
size_t found = input[i].find("MCD");
if(found != string::npos) cnt++;
while(found != string::npos){
found = input[i].find("MCD",found+1,3);
if(found != string::npos) cnt++;
}
}
cout << cnt;
return 0;
}