본문 바로가기

Algorithm/BAEKJOON

[BOJ] 7656번 만능 오라클 (C++)

728x90
반응형

https://www.acmicpc.net/problem/7656

 

7656번: 만능 오라클

입력은 한 줄로 된 1000자 이내의 단락이 주어진다. 포함된 문자는 대소문자, 띄어쓰기, 하이픈(hyphen), 어퍼스트로피(apostrophe), 반점(comma), 세미콜론(semicolon), 온점(period)과 물음표(question mark)이다.

www.acmicpc.net

 

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

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	string str;
	getline(cin, str);
	
	int start, end = -1;
	while(str.find("What", end + 1) != -1){
		start = str.find("What", end + 1);
		end = str.find("?", start + 1);
		string s = str.substr(start, end - start + 1);

		if(s.find(".") != -1){
			end = str.find(".", start + 1);
			continue;
		}
		s.replace(0, 4, "Forty-two");
		s.replace(s.length() - 1, 1, ".");
		cout << s << endl;
	}
	return 0;
}

 

먼저 "What"이 처음 나온 인덱스를 start에 넣고, "?"이 처음 나온 인덱스를 end에 넣는다. 문자열은 마침표 또는 물음표로 끝난다고 했으므로 마침표로 끝나는지 검사하기 위해서 start부터 end 인덱스까지를 s로 설정하고 s 안에 마침표가 있는지 확인한다.

- 있다면 end를 마침표가 있는 인덱스로 바꾼다.

- 없다면 s의 "What"을 "Forty-two"로, "?"를 "."으로 바꾸어 출력한다.

 

end + 1 인덱스부터 위 과정을 반복한다.

728x90
반응형