# 문제
# 입력 및 출력
# 풀이
이 문제도 처음엔 내가 하나하나 비교하는 조건문으로 풀었는데 바로 밑에 짧게 푼 코드가 있어서 써봤다,,
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
cin >> input;
int i = 0, count = 0;
while (i < input.size()) {
if (input[i] == 'c') {
if (input[i + 1] == '=' || input[i + 1] == '-') i++;
}
else if (input[i] == 'd') {
if (input[i + 1] == 'z'&&input[i + 2] == '=') i += 2;
else if (input[i + 1] == '-') i++;
}
else if (input[i] == 'l') {
if (input[i + 1] == 'j') i++;
}
else if (input[i] == 'n') {
if (input[i + 1] == 'j') i++;
}
else if (input[i] == 's') {
if (input[i + 1] == '=') i++;
}
else if (input[i] == 'z') {
if (input[i + 1] == '=') i++;
}
i++;
count++;
}
cout << count << endl;
}
다른 사람 코드를 보니 string::find 함수를 사용해서 문자열에 찾는 문자열이 있는지 확인하고 있으면
string::replace 함수를 이용해서 알파벳을 하나로 바꿔준다
string::find 함수는 문자열을 찾는데 성공하였다면, 해당 문자열의 시작 위치 를 반환하고,
찾지 못한다면 npos 를 리턴 npos 는 string::npos 로 정의되는 상수이다
#include <iostream>
#include <string>
using namespace std;
string alphabet[8] = { "c=","c-","dz=","d-","lj","nj","s=","z=" };
int main() {
string input;
cin >> input;
for (int i = 0; i < size(alphabet); i++) {
while (1) {
int index = input.find(alphabet[i]);
if (index == string::npos) break;
else input.replace(index, alphabet[i].size(), "a");
}
}
cout << input.size() << endl;
}
찾고자 하는 크로아티아 알파벳이 여러개일 경우를 대비해 for문 안에서 반복문을 따로 설정해준다
크로아티아 알파벳이 없을 경우 index==npos가 되고 다음 반복문으로 넘어가게 됨
크로아티아 알파벳을 찾았으면 나중에 알파벳 개수를 세기 쉽게 "a"로 바꿔줌
replace함수의 인자는 아래 블로그 참고
https://popawaw.tistory.com/53
c++ 문자열 일부 교체하기(replace)
#include #include using namespace std; int main() { string sentence = "i like coding"; string find_str = "coding"; string replace_str = "history"; sentence.replace(sentence.find(find_str), find_str...
popawaw.tistory.com
최종 결과는 크로아티아 알파벳은 전부 a로 바꾼 input 변수의 크기가 됨
여러 함수를 사용해서 짧고 가독성있게 코드를 작성하는 것이 좋다고 본다
내가 본 코드를 작성한 사람이 숭실대던데
몇문제 안풀었는데 엄청 잘풀었더라ㅋㅋㅋ,,,
나도 열심히 해야지ㅋㅋㅎ
댓글