[c++] string.find() - 문자열에서 특정 문자열 찾기

강신현·2022년 6월 24일
0

✅ string.find()

string.find()

https://modoocode.com/241

문자열에서 원하는 문자열의 위치를 찾는다.

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;

- 파라미터

  • str - 찾고자 하는 문자열
  • pos - 검색을 시작할 위치
  • count - 찾고자 하는 문자열의 길이
  • s - 찾고자 하는 문자열을 가리키는 포인터
  • ch - 찾고자 하는 문자
  • t - 찾고자 하는 string_view 로 변환 가능한 객체

- 리턴값

문자열을 찾는데

  • 성공 : 해당 문자열의 시작 위치를 반환한다.
  • 실패 : npos 를 리턴한다.
    npos 는 string::npos 로 정의되는 상수

예시 문제

해결 로직

  1. 한문장 안에 MCD가 여러개 있을 수 있다.
  2. 따라서 찾기 시작할 위치를 알아야 하므로 첫번째 MCD를 찾고 두번째 부터는 전 위치의 다음 위치부터 탐색한다.
  3. 주의해야 할 점은 특정 위치에서 끝까지 탐색하면 중복되서 세어지므로 특정 위치에서 찾는 문장의 길이 만큼만 탐색해야 한다.

코드

#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;
}
profile
땅콩의 모험 (server)

0개의 댓글