c,c++/c++ 관련 개념 및 문법

C++ 문자열 parsing

YoonJongSeok 2023. 8. 22. 01:13

C++ 문자열 parsing을 위해 3가지 메서드를 소개한다.

 

1) substr 메서드

2) find 메서드

3) getline 메서드

 

1) substr 예시 code

string str = "stringParse";
string result = str.substr(0, 6);
// result : string

0 ~ 5의 인덱스에 해당하는 문자열을 가져오게 된다.

2) find 예시 code

string str = "get stringhind";
int num = str.find("stringhind");
//num : 4

stringbind의 시작 위치를 반환한다. 

3) getline 예시

cin 이용 시 공백 문자를 입력하면 공백 문자 전까지만 읽어들이게 된다. getline을 이용하면 공백을 포함한 문자 모두를 입력 받는다.

string str;
getline(cin, str);

cin 이용 시 또 조심할 것은 엔터를 누르면 buffer에 남게 되는데 해당 버퍼는 다음 cin에서 또 입력으로 들어가기 때문에 문제가 생긴다. 이것은 ignore() 메서드로 지워줘야한다. cin.ignore()을 이용하면 1 문자의 버퍼를 제거하게 되는 것이고 cin.ignore(3) 이라면 3문자 버퍼를 제거하는 것이다.

 

문자열 parsing

vector의 push_back, size, pop_back 같은 명령를 입력 받았을 때 명령과 값을 따로 parsing하여 동작하는 작동을 해보자

int N;
	string str;
	string delim = " ";
	vector<int> result; // 실제 값이 들어갈 vector
	vector<string> temp; // 명령과 값을 구분할 임시 vector
	size_t position; // delim의 위치를 찾는 변수
	cin >> N; // 간단하게 N번 반복한다.
	cin.ignore(); // cin buffer 제거
	for (int i = 0; i < N; i++)
	{
		int num;
		getline(cin, str);
		while ((position = str.find(delim)) != string::npos) // find the delim string in str if find, return position of the delim str, otherwise return npos
		{
			temp.push_back(str.substr(0, position)); // push the string by position - 1 
			str.erase(0, position + delim.length()); // erase by position + delim.length() -1
		}
		if (str.compare("size") == 0) // 명령어의 유형에 따라 분기문을 잘 선택, 그렇지 않으면 없는 temp값에 접근하게 됨
		{
			cout << result.size() << endl;
		}
		else if (str.compare("pop_back") == 0)
		{
			result.pop_back();
		}
		else if (temp[0].compare("push_back") == 0)
		{
			temp.push_back(str);
			num = stoi(temp[1]);
			result.push_back(num);
		}
		else if (temp[0].compare("get") == 0)
		{
			temp.push_back(str);
			num = stoi(temp[1]);
			if (result.size() < num) {
				cout << "out of range" << endl;
				continue;
			}
			cout << result[num-1] << endl;
		}
		temp.clear();
	}

string compare 메서드

string과 비교하는데 서로 같다면 0을 왼쪽 string( 비교하는 주체 *this) 가 크다면 양수 값

왼쪽 string( 비교하는 주체 *this) 가 작다면 음수 값을 return한다.