프로그래밍 언어/C++
[C/C++ 2.4] 문자열 Parsing
물꼮이
2022. 3. 10. 09:58
문제)
정답코드)
// parsing 예제 ___strtok 금지
#include<string>
#include<vector>
// 1번 : ABC가 몇개 인지 출력
void count_ABC(string str) {
int j = 0;
int cnt = 0;
while (str[j] != '\0') {
if (str[j] == 'A' && str[j + 1] == 'B' && str[j + 2] == 'C')
cnt++;
j++;
}
cout << "1번답 : " << cnt << endl;
}
// 2번 : 괄호 안에 숫자들의 합 출력 **** 암기 !!! 연습 !!! 정리 !!!!
void sum_Int(string str) {
int sum = 0;
int a=0, b=0;
while (1) {
// 특정 문자 사이의 문자열을 parsing 하는 로직
a = str.find('[', b);
if (a == -1) break; //문장 한바퀴 다 돌면 멈춤
b = str.find(']', a + 1); // str.find('문자열', 탐색시작 index) → 탐색시작 index부터 '문자열'을 찾기 시작해, 찾으면 index값으로 반환
int size = b - a - 1;
string tmp = str.substr(a + 1, size); // str.substr(시작index. size) → str의 시작 inde부터 size만큼을 substring 으로 빼서 반환
sum += stoi(tmp);
}
cout << "2번 답 : " << sum;
}
//3번 : ????
int split_bar(string str){
//| 스플릿
vector<string> top;
str += "|";
int a = 0;
int b = 0;
while (1) {
b = str.find('|', a);
if (b == -1) break;
int size = b - a;
string temp = str.substr(a, size);
top.push_back(temp);
a = b + 1;
}
}
// 4번 : '|' bar를 기준으로 split 하여 출력하기
void split_out(string str){
int a = -1;
int cnt = 0;
while (1) {
a = str.find("ABC", a + 1);
if (a == -1) break;
cnt++;
}
cout << cnt;
}
int main() {
string str = "ABC[123]DA|DA[45]DQ|W|ABC";
count_ABC(str);
sum_Int(str);
split_bar(str);
split_out(str);
return 0;
}