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