개요
문자열을 split하는 방법에는 수많은 방법이 존재하겠지만, 내가 사용할 방법에 대해 정리해놓기 위한 글이다.
나는 istringstream를 적절히 사용할 예정이다.
두 함수는 #include <sstream> 헤더를 포함시켜야 한다.
isstringstream : 문자열을 parsing하기 위함
isstringstream
1. 가장 기본적인 사용 방법
Defalut로, istringstream은 공백(' ')을 기준으로 split(쪼갬)
getline의 인자에 ','를 넣어주면 콤마(,)를 기준으로 split도 가능함
-> 즉, 공백 이외에도 다양한 구분자를 사용할 수 있음
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string s = "Hello my name is Kang";
istringstream iss(s); // iss를 통해 s를 자를 준비가 되었다고 생각하자
string temp; // split된 문자열을 저장
while (getline(iss, temp, ' ')) { // 공백(' ')을 기준으로 split하겠다
cout << temp << '\n'; // 상황에 맞게 vector에 담거나 해도 됨
}
return 0;
}
[출력]
Hello
my
name
is
Kang
2. 다른 사용 방법
문자열에서 split된 token을 자료형에 맞추어 저장할 수도 있다.
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string s = "hello 123 bye 45678";
istringstream iss(s);
string str1, str2; int n1, n2;
iss >> str1 >> n1 >> str2 >> n2; // 이 코드가 꼭 필요함
cout << str1 << '\n';
cout << n1 << '\n';
cout << str2 << '\n';
cout << n2;
return 0;
}
[출력]
hello
123
bye
45678
'알고리즘 정리' 카테고리의 다른 글
[알고리즘] 다익스트라(Dijkstra) (0) | 2023.09.28 |
---|---|
PS 문제 풀이 일지 (~ing) (0) | 2023.07.30 |
개요
문자열을 split하는 방법에는 수많은 방법이 존재하겠지만, 내가 사용할 방법에 대해 정리해놓기 위한 글이다.
나는 istringstream를 적절히 사용할 예정이다.
두 함수는 #include <sstream> 헤더를 포함시켜야 한다.
isstringstream : 문자열을 parsing하기 위함
isstringstream
1. 가장 기본적인 사용 방법
Defalut로, istringstream은 공백(' ')을 기준으로 split(쪼갬)
getline의 인자에 ','를 넣어주면 콤마(,)를 기준으로 split도 가능함
-> 즉, 공백 이외에도 다양한 구분자를 사용할 수 있음
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string s = "Hello my name is Kang";
istringstream iss(s); // iss를 통해 s를 자를 준비가 되었다고 생각하자
string temp; // split된 문자열을 저장
while (getline(iss, temp, ' ')) { // 공백(' ')을 기준으로 split하겠다
cout << temp << '\n'; // 상황에 맞게 vector에 담거나 해도 됨
}
return 0;
}
[출력]
Hello
my
name
is
Kang
2. 다른 사용 방법
문자열에서 split된 token을 자료형에 맞추어 저장할 수도 있다.
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
string s = "hello 123 bye 45678";
istringstream iss(s);
string str1, str2; int n1, n2;
iss >> str1 >> n1 >> str2 >> n2; // 이 코드가 꼭 필요함
cout << str1 << '\n';
cout << n1 << '\n';
cout << str2 << '\n';
cout << n2;
return 0;
}
[출력]
hello
123
bye
45678
'알고리즘 정리' 카테고리의 다른 글
[알고리즘] 다익스트라(Dijkstra) (0) | 2023.09.28 |
---|---|
PS 문제 풀이 일지 (~ing) (0) | 2023.07.30 |