[C++/Algorithm] STL : String::find()의 응용

정건희·2024년 11월 15일

STL/알고리즘

목록 보기
1/10

1. String::find()는..

C++에서 문자열 내의 특정 문자, 혹은 문자열의 첫 번째 발생 위치를 찾는 데 사용된다. 여러 번 등장하더라도 가장 먼저 등장하는 위치만 반환되기 때문에, 여러 개의 대상을 찾아낼 때 어떻게 응용되는지 구현해보았다.


2. 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(char c, size_t pos = 0) const;
  • str 또는 s: 찾고자 하는 문자열 또는 문자입니다.
  • pos: 검색을 시작할 위치 (기본값은 0).
    반환값
  • 찾았을 경우: 문자열 내에서 찾은 첫 번째 위치의 인덱스(size_t)를 반환합니다.
  • 찾지 못했을 경우: string::npos를 반환합니다.

예제

문자 검색
#include <iostream>
#include <string>

using namespace std;

int main() {
    string text = "Hello, World! Hello, Universe!";
    
    size_t pos = text.find('o');  // 'o'를 찾음
    cout << "First 'o': " << pos << endl;  // 출력: 4

    pos = text.find('o', pos + 1);  // 다음 'o'를 찾음
    cout << "Second 'o': " << pos << endl;  // 출력: 8

    return 0;
}
문자열 검색
#include <iostream>
#include <string>

using namespace std;

int main() {
    string text = "abc abc abc";
    
    size_t pos = text.find("abc");  // "abc"를 찾음
    cout << "First 'abc': " << pos << endl;  // 출력: 0

    pos = text.find("abc", pos + 1);  // 다음 "abc"를 찾음
    cout << "Second 'abc': " << pos << endl;  // 출력: 4

    return 0;
}



3. 찾는 문자열이 여러 개일 경우

find()는 하나의 문자나 문자열만 처리할 수 있으므로, 여러 문자를 동시에 찾으려면 다른 방법을 사용해야 한다.
for 또는 std::find_first_of를 사용한다.

여러 문자 중 첫 번째로 등장하는 위치 찾기

#include <iostream>
#include <string>

using namespace std;

int main() {
    string text = "apple pie and banana";
    string chars = "aeiou";  // 모음

    size_t pos = text.find_first_of(chars);
    cout << "First vowel: " << text[pos] << " at position " << pos << endl;

    return 0;
}

출력

First vowel: a at position 0



4. 결과

  1. string::find()는 첫 번째로 등장한 위치만 반환합니다.
    • 동일한 문자나 문자열이 여러 번 등장하더라도, 가장 앞에 있는 것만 반환.
  2. 여러 번 등장한 경우
    • 다음 위치를 찾으려면 pos를 조정하여 반복적으로 호출.
  3. 여러 문자나 문자열 중 하나를 찾으려면:
    • find_first_of를 사용하거나, 반복문으로 각 문자를 개별적으로 찾는 방식으로 구현.


5. std::find_first_of

std::find_first_of는 C++ 표준 라이브러리의 헤더에 포함된 알고리즘으로, 주어진 범위에서 특정 요소들 중 첫 번째로 나타나는 요소를 찾는 함수입니다.

이 함수는 두 범위를 비교하여, 첫 번째 범위에서 두 번째 범위에 포함된 요소가 발견되면 해당 위치의 반복자(iterator)를 반환합니다.

template<class InputIterator, class ForwardIterator>
InputIterator find_first_of(InputIterator first1, InputIterator last1,
                            ForwardIterator first2, ForwardIterator last2);

template<class InputIterator, class ForwardIterator, class BinaryPredicate>
InputIterator find_first_of(InputIterator first1, InputIterator last1,
                            ForwardIterator first2, ForwardIterator last2,
                            BinaryPredicate p);

매개변수

  1. first1, last1: 첫 번째 범위 (검색할 대상).
  2. first2, last2: 두 번째 범위 (찾으려는 요소들).
  3. p (선택적): 요소 비교를 위한 사용자 정의 Binary Predicate 함수(참/거짓 반환).

반환값

  • 첫 번째 범위에서 두 번째 범위의 요소 중 하나를 찾은 위치의 반복자(iterator)를 반환합니다.
  • 찾지 못하면 첫 번째 범위의 끝(last1)을 반환합니다.

작동 방식

  1. 첫 번째 범위 ([first1, last1))의 각 요소를 순차적으로 검사합니다.
  2. 각 요소가 두 번째 범위 ([first2, last2))에 포함되어 있는지 확인합니다.
  3. 포함되어 있다면 해당 요소의 반복자를 반환합니다.




사용 예시

1. 기본 사용

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
  vector<int> v1 = {1, 2, 3, 4, 5};
  vector<int> v2 = {4, 6, 7};  // 찾으려는 값들

  // 첫 번째 범위에서 두 번째 범위의 첫 번째 값을 찾음
  auto it = find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end());

  if (it != v1.end()) {
      cout << "First matching element: " << *it << endl; // 출력: 4
  } else {
      cout << "No matching element found!" << endl;
  }

  return 0;
}

출력:

First matching element: 4



2. 사용자 정의 비교 함수

find_first_of에 Binary Predicate를 제공하면, 사용자 정의 조건을 기준으로 값을 찾을 수 있습니다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype> // for ::tolower

using namespace std;

// 대소문자 무시 비교 함수
bool case_insensitive_compare(char a, char b) {
  return tolower(a) == tolower(b);
}

int main() {
  string str1 = "Hello, World!";
  string str2 = "ow";

  // 대소문자를 무시하고 검색
  auto it = find_first_of(str1.begin(), str1.end(),
                          str2.begin(), str2.end(),
                          case_insensitive_compare);

  if (it != str1.end()) {
      cout << "First matching character: " << *it << endl; // 출력: o
  } else {
      cout << "No matching character found!" << endl;
  }

  return 0;
}

출력:

First matching character: o

0개의 댓글