관리 메뉴

JIE0025

[ C++ ] 문자열 치환 replace, regex_replace 본문

기타 학습/Language

[ C++ ] 문자열 치환 replace, regex_replace

Kangjieun11 2022. 5. 19. 20:29
728x90

 

replace

문자열 시작위치부터 지정 길이까지 치환할 문자로 변환한다.

 

문자열.replace(시작위치,길이, 치환할문자열)
#include<iostream>
#include<string>
using namespace std;

int main(){

	string s = "abcde"
	s.replace(0,3,"zzz");
	// zzzde
   	
    return 0;
}

 

 

regex_replace

문자열에서 문자를 검색해 치환하는 함수이다. 

regex는 정규표현식 관련 라이브러리인데 

정규표현식으로 치환할 문자열을 주면 된다. 

 

 

#include <regex>
regex_replace(문자열, regex(정규식), 치환할문자열)

 

#include<regex>
#include<iostream>
#include<string>
using namespace std;

int main(){
	string s = "hello my name is gildong";
    s = regex_replace(s, regex("gildong"), "hong");
	
    //hello my name is hong
	
    return 0;
}