컴퓨터/알고리즘

[백준 1543번] 문서 검색 (c++ <string> 레퍼런스 )

https://www.acmicpc.net/problem/1543

 

1543번: 문서 검색

세준이는 영어로만 이루어진 어떤 문서를 검색하는 함수를 만들려고 한다. 이 함수는 어떤 단어가 총 몇 번 등장하는지 세려고 한다. 그러나, 세준이의 함수는 중복되어 세는 것은 빼고 세야 한

www.acmicpc.net


1. 생성자

  1. 사전에 선언한 스트링 이용하기
    • s2 = s0;
    • s2 = (s0);
    • s2 = (s0,firstIndexPos, stringlen)
      • firstIndexPos : s0 문자열을 여기서부터 서브스트링을 넣어주고 싶다!
        할때 시작 기준 (인덱스)
      • stringlen : 서브 스트링의 길이
        얼만큼 넣어주고 싶니?
    • s2 = (s0.begin(), s0.begin + len)
  2. 특정 문자로 fill 하고싶다.
    • s6 (10, char) //char로 10길이만큼 채우기

2. find, substr

1. find

대상문자열.find(토큰)

  • return
    • 찾았음 : 시작인덱스 //뭐.. 배열 인덱스처럼 숫자로 나오겠지?
    • 못찾음 : string::npos //이게 값 자체이니깐 | str.find("~") != string::npos | 라고 쓰면 OK!

2. substr

  1. substr(index) : 찾은 문자도 포함해서 끝까지 서브스트링
    • 만약 찾은 문자가 char 하나라면 하나만 잘라내고 서브스트링하는것
  2. substr(index, len) : index부터 시작해서 len 까지

3. 기타

1. erase(index, len)

2. stoi("문자열") : str -> int

3. to_string(int) : int-> str

4. isdigit & isalpha

5. isupper & islower : 대소문자

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
int main()
{
    ios::sync_with_stdio(false); cin.tie(NULL);
    string str, token;
    getline(cin, str); getline(cin, token);
    int cnt = 0int start = 0;
    while (str.find(token) != string::npos)
    {
        int firstCharPos = str.find(token);cnt++;
        str = str.substr(firstCharPos+token.length(), str.length());
    }
    cout << cnt << '\n';
    return 0;
}
 
cs