STL - string - Replace(펌)

2019. 12. 16. 16:07카테고리 없음

반응형

참고하려고 저장해둬요

 

(펌 : https://hashcode.co.kr/questions/239/%EC%8A%A4%ED%8A%B8%EB%A7%81%EC%97%90%EC%84%9C-%ED%8A%B9%EC%A0%95-%EB%8B%A8%EC%96%B4-%EA%B5%90%EC%B2%B4%ED%95%98%EA%B8%B0)

1. boost 사용

#include <boost/algorithm/string/replace.hpp>

 

// 원본 스트링을 바꾸는 경우

std::string in_place = "blah#blah";

boost::replace_all(in_place, "#", "@");

 

// 원본 스트링을 바꾸지 않고 다른 스트링에 저장하는 경우

const std::string input = "blah#blah";

std::string output = boost::replace_all_copy(input, "#", "@");

 

2. string::find() 사용

 

std::string ReplaceAll(std::string &str, const std::string& from, const std::string& to){ size_t start_pos = 0; //string처음부터 검사 while((start_pos = str.find(from, start_pos)) != std::string::npos) //from을 찾을 수 없을 때까지 { str.replace(start_pos, from.length(), to); start_pos += to.length(); // 중복검사를 피하고 from.length() > to.length()인 경우를 위해서 } return str; } ... std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl; std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl; std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

 

3. 번외 - 철자 하나만 바꾸는 경우 - <algorithm>의 replace()

#include <algorithm>

#include <string>

int main()

{

std::string s = "example string";

char from = 'e';

char to = '!';

std::replace( s.begin(), s.end(), from, to);

 

// replace all 'x' to 'y'

std::cout << s << endl;

}

 

결과)

!xampl! string