본문 바로가기

언어/C++

4장 3번 - 문장입력하고 부분 문자 바꾸기

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char** argv) {
	string str;
	srand( (unsigned)time(0) );
	string alpa[26]={"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
					"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
					"w", "x", "y", "z"};
	int cstr;
	int calpa;
	cout << "아래에 한 줄을 입력하세세요 (exit를 입력하면 종료합니다.)"<< endl;				
	while(1){
		cout << ">> ";
		getline(cin,str);
		

		if(str=="exit")break;
		
		cstr=rand()%str.size();
		calpa=rand()%26;
		str.replace(cstr,1,alpa[calpa]);
		
		cout <<str<<endl;
		
		
	}
	return 0;
}

 

설명 > 

 

replace (cstr, 1, alpa[alpa] ) ;

기존 문자열의 pos 부터 count 개 만큼, 혹은 first 부터 last 까지를 string_view 로 변환 가능한 타입 t 로 치환한다

 

 

calpa =rand() %26;

alpha 배열을 만들어서 alpa[calpa] 로 이용한다