🌍 C++ Study/C++ 기초
C++ string replace 문자열 바꾸기
맨텀
2024. 11. 10. 02:19
1. std::string::find 와 함께 std::string::replace 를 사용하는 경우
위치를 알고있으면 바로 string::replace를 사용하면 된다.
1) 발견되는 첫 번째 문자열을 바꾸는 방법
첫 번째 인자 : 시작 지점의 인덱스
두 번째 인자 : 대체할 길이
세 번째 인자 : 대체할 문자
std::string str = "Hello, World!";
std::string to_replace = "World";
std::string replacement = "C++";
// 찾고 치환
size_t pos = str.find(to_replace); // "World"의 위치 찾기
if (pos != std::string::npos) {
str.replace(pos, to_replace.length(), replacement);
}
2) 모든 일치 문자열을 치환 : 발견되지 않을때 까지 반복문을 사용하자
std::string str = "Hello, World! World is great.";
std::string to_replace = "World";
std::string replacement = "C++";
size_t pos = 0;
while ((pos = str.find(to_replace, pos)) != std::string::npos) {
str.replace(pos, to_replace.length(), replacement);
pos += replacement.length(); // 다음 검색 위치를 설정
}
2. std::regex_replace를 사용하는 방법 (C++17 이상)
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str = "My, Test Project!";
std::regex pattern("Test");
std::string to = "End";
str = std::regex_replace(str, pattern, to); // 결과값 : My, End Project
return 0;
}