1. find
- 찾으려고 하는 문자 혹은 문자열의 시작 위치 index를 size_t 타입으로 리턴
- 찾는 문자가 없는 경우 string::npos 값을 리턴 (18446744073709551615 가 출력된다)
- find에 두번째 매개변수를 넣으면, 해당 위치부터 시작해서 find 함수를 수행할 수도 있다.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello,World\n";
//특정 문자의 위치 찾기
size_t pos1 = str.find(',');
size_t pos2 = str.find("ZZ");
size_t pos3 = str.find("H", 1);
cout << pos1 << "\n"; //5
cout << pos2 << "\n"; //string::npos
cout << pos3 << "\n"; //string::npos
}
2. replace
- 파라메터
- 첫번째 : 시작 위치 인덱스
- 두번째 : 끝 위치 인덱스
- 세번째 : 대체할 문자열
- [시작위치, 끝위치) 를 없애주고, 그 대신 대체할 문자열을 넣어준다.
- 없애는 길이와 문자열의 길이 상관없이
- 시작위치에서 끝위치까지의 값을 일단없애고, 대체 문자열을 넣어주는 방식이다.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello,World\n";
//특정 위치를 찾아서 다른 문자로 대체(삭제)하기
size_t pos = str.find("World");
str.replace(pos, pos + 5, "");
cout << str << "\n"; //Hello,
cout << str.size() << "\n"; //6
string str2 = "abcdefg";
str2.replace(0, 3, "zzzzz");
cout << str2 << "\n"; //zzzzzdefg
string str3 = "abcdefg";
str3.replace(0, 5, "z");
cout << str3 << "\n"; //zfg
}
'알고리즘(코딩테스트)' 카테고리의 다른 글
1, 2 주차 알고리즘 정리 (0) | 2025.02.17 |
---|---|
알고리즘 관련 함수 1 (0) | 2025.02.12 |
우선순위 큐, 순열, k값 찾기 (0) | 2025.02.10 |
map & set (0) | 2025.02.05 |
unordered_map 순환 (1) | 2025.02.04 |