어제의 나보다 성장한 오늘의 나

[c++] 문자열 찾기 ( <algorithm> find , <string> find) 총정리 및 예제 본문

c++/문법

[c++] 문자열 찾기 ( <algorithm> find , <string> find) 총정리 및 예제

today_me 2022. 2. 19. 21:30
반응형

<string> 에서 제공하는 Find 함수가 있고, <algorithm> 에서 제공하는 Find 함수가 있는데 두 가지를 모두 정리해보았다.

 

① <string> 의 find 함수

 

 

헤더파일

#include <string>

 

사용법

 

s.find( 찾을 문자열 , 시작 위치 , 찾을 문자열의 길이 )

string s = "Hello My Name is metoday.";

int non;
non = s.find("h"); //non == npos

cout << s.find("e"); // 출력 : 1
cout << s.find("e" , 2); // 출력 : 12
cout << s.find("Myapple" , 5 , 2) // 출력 : 6

◎ 대소문자 구별을 하기 때문에 h를 찾지 못했다. 찾지 못하면 npos를 반환 한다.

◎ 찾고자 하는 문자가 여러개 있을 때 시작 위치를 잘 설정하면 원하는 문자의 위치를 얻을 수 있다.

◎ 찾을 문자열의 길이가 2로 입력 되었기 때문에 "Myapple"에서 "My"를 찾게 설정되어서 6이 출력 된 것이다.

 

npos 활용법

 

string s = "Hello World";

int index = s.find("a");

if(index == string::npos){
	cout << "Not Found."
}

else{
	cout << index ;
}

// 출력 : Not found.
반응형

② <algorithm> 의 find 함수

 

vector에서의 사용

 

find( v.begin() , v.end() , 찾을값 ) 

vector<int> v = {2 , 1 , 4 , 5 , 3};
vector<int> :: iterator it;

it = find( v.begin() , v.end() , 3 );
cout << *it << endl; // 출력 : 3 
cout << it - v.begin() << endl; // 출력 : 4

find는 찾는 값을 가리키고 있는 iterator를 반환한다.

그래서 *를 붙이면 it가 가리키는 값을 반환하고,

it - v.begin()을 해주면 가리키는 값의 index를 반환한다.

 

찾는 값이 없을 경우

vector<int> v = {2 , 1 ,4 ,5 ,3};
vector<int> :: iterator it;

it = find(v.begin() , v.end() , 6);

cout << *it <<endl; // 출력 : 0
cout << it - v.begin(); // 출력 : 5

값이 없어 못 찾았을 때 it는 v.end를 가리키게 된다.

 

v.end를 가리키는 것을 확인하는 예시 Coding

vector<int> v = {1, 2, 3, 4, 5};
vector<int>::iterator it;

it = find(v.begin() , v.end() , 6);
if(it == v.end()){
	cout << "Not Found.";
}
else{
	cout << "index : " << it - v.begin() ;
}

//출력 : Not Found.

 

array 에서의 사용

 

find( arr , arr + arr_size , 찾을 값 )

int arr[] = { 1 , 3 , 5 , 2 , 6 };
int* p;

p = find( arr , arr+5 , 6 );

cout << *p << endl; // 출력 : 6
cout << p - arr ; // 출력 : 4

array의 find는 포인터로 받는다. 

*을 붙이면 포인터가 가리키는 값을 반환한다.

p - arr를 하면 포인터가 가리키는 값의 index를 반환한다.

 

 

찾는 값이 없을 경우

int arr[] = { 1 , 3 , 5 , 2 , 6 };
int* p;

p = find(arr , arr+ 5 ,20);

cout << *p << endl; // 출력 : 쓰레기값
cout << p - arr ; // 출력 : 5

 

값이 없어 찾지 못했을 때는 p는 arr + arr_size를 가리킨다.

 

 

arr+ arr_size를 가리키는 것을 확인하는 예시 Coding

int arr[] = {1 , 2, 3 ,4 ,5};
int* p ;
p = find( arr , arr + 5 , 6 );

if(p == arr + 5){
    cout << "Not Found.";
}
else{
    cout << "index : " << p - arr ;
}
// 출력 : Not Found.
반응형
Comments