티스토리 뷰

  • 먼저 첫번째로 Position을 통한 파싱 방법이다. 아래의 코드를 보게 되면, Fpos, Lpos 두개의 변수를 선언하게 되는데, 각각 find_first_not_of, find_first_of 를 통해서 값을 받는다.
  • size_t find_first_not_of(const char* s, size_t pos); -> str에서 s의 값이 아닌 첫 번째 위치 반환.
  • size_t find_first(const char* s, size_t pos); -> str에서 s의 값이 존재하는 첫 번째 위치 반환.
  • 이렇게 반환한 값을 토대로, substr을 하면서 값을 나눈다.
#include <iostream>
#include<vector>
#include <string>

void parse_to_position(const string& str, vector<string>& values, const string delimiter) {
	// str : 전체 문자열
	// values : sub string을 저장할 벡터
	// delimiter : 파싱 기준 구획 문자

	string::size_type Fpos = str.find_first_not_of(delimiter, 0);
	string::size_type Lpos = str.find_first_of(delimiter, Fpos);

	while (string::npos != Fpos || string::npos != Lpos) {
		values.push_back(str.substr(Fpos, Lpos - Fpos));
		Fpos = str.find_first_not_of(delimiter, Lpos);
		Lpos = str.find_first_of(delimiter, Fpos);
	}
}

int main() {
	int n;
	std::string s1 = "I Hope You baby, me Dalling";
	vector<string> parsing1;
	parse_to_position(s1, parsing1, " ");
	std::cout << " Parsing 1 : Position " << endl;
	for (string a : parsing1)
		cout << a << endl;
	cout << endl;
}

  • 아래의 코드는 위 방식과는 반대로, 기본 문자열인 str을 erase를 통해서 잘라가면서 집어넣는 방식이다. 따라서 인자를 보면 레퍼런스가 아니라 값 자체를 받는 것을 볼 수 있다.
#include <iostream>
#include<vector>
#include <string>

using namespace std;

void parse_to_remove(string str, vector<string>& values, const string delimiter) {

	int pos = 0;
	string token;
	while ((pos = str.find(delimiter)) != string::npos) {
		token = str.substr(0, pos);
		values.push_back(token);
		str.erase(0, pos + delimiter.length());
	}
	values.push_back(str);
}

int main(){
	std::string s2 = "Holly Molly Dully Dash Cash Men";
	vector<string> parsing2;
	parse_to_remove(s2, parsing2, " ");
	std::cout << "Parsing 2 : Remove " << endl;
	for (string a : parsing2)
		cout << a << endl;
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함