C ++에서 문자열의 일부를 다른 문자열로 바꿀 수 있습니까?
기본적 으로이 작업을 수행하고 싶습니다.
QString string("hello $name");
string.replace("$name", "Somename");
그러나 Standard C ++ 라이브러리를 사용하고 싶습니다.
답변
문자열 ( find
) 내에서 하위 문자열을 찾는 기능 과 문자열 의 특정 범위를 다른 문자열 ( replace
) 로 바꾸는 기능이 있으므로 원하는 효과를 얻기 위해 이들을 결합 할 수 있습니다.
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string string("hello $name");
replace(string, "$name", "Somename");
의견에 대한 응답으로 replaceAll
아마도 다음과 같이 보일 것입니다.
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
답변
C ++ 11을 사용하면 다음 std::regex
과 같이 사용할 수 있습니다 .
#include <regex>
...
std::string string("hello $name");
string = std::regex_replace(string, std::regex("\\$name"), "Somename");
이스케이프 문자를 이스케이프 처리하려면 이중 백 슬래시가 필요합니다.
답변
std::string
가 replace
당신을 위해 무엇을 찾고있는 것을, 방법을 무엇입니까?
시도해 볼 수 있습니다 :
s.replace(s.find("$name"), sizeof("$name") - 1, "Somename");
난 그냥에 대한 설명서를 읽고, 자신을 시도하지 않은 find()
및 replace()
.
답변
새 문자열을 반환하려면 다음을 사용하십시오.
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
성능이 필요한 경우 입력 문자열을 수정하는 최적화 된 함수는 다음과 같습니다. 문자열의 복사본을 만들지 않습니다.
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
테스트 :
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
산출:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
답변
예, 할 수 있지만 string의 find () 멤버로 첫 번째 문자열의 위치를 찾은 다음 replace () 멤버로 바꿔야합니다.
string s("hello $name");
size_type pos = s.find( "$name" );
if ( pos != string::npos ) {
s.replace( pos, 5, "somename" ); // 5 = length( $name )
}
표준 라이브러리를 사용할 계획이라면, 이 모든 것들을 아주 잘 다루는 C ++ 표준 라이브러리 책 의 사본을 실제로 얻어야 합니다.
답변
나는 일반적으로 이것을 사용한다 :
std::string& replace(std::string& s, const std::string& from, const std::string& to)
{
if(!from.empty())
for(size_t pos = 0; (pos = s.find(from, pos)) != std::string::npos; pos += to.size())
s.replace(pos, from.size(), to);
return s;
}
아무것도 찾을 std::string::find()
때까지 검색된 문자열의 다른 항목을 찾기 위해 반복적으로 호출 합니다 std::string::find()
. 일치 std::string::find()
하는 위치 를 반환 하기 때문에 반복자를 무효화하는 데 문제가 없습니다.
답변
이것은 옵션처럼 들립니다
string.replace(string.find("%s"), string("%s").size(), "Something");
이것을 함수로 포장 할 수는 있지만이 한 줄 솔루션은 받아 들일 수 있습니다. 문제는 이것이 첫 번째 발생만을 변경한다는 것입니다. 반복하고 싶을 수도 있지만 동일한 토큰 ( %s
) 을 사용 하여이 문자열에 여러 변수를 삽입 할 수도 있습니다