첫 번째 방법은 stringstream을 사용하여 공백으로 구분된 단어를 읽는 것입니다. 이것은 약간 제한적이지만 적절한 검사를 제공하면 작업을 상당히 잘 수행합니다.
예
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str("Hello from the dark side");
string tmp; // A string to store the word on each iteration.
stringstream str_strm(str);
vector<string> words; // Create vector to hold our words
while (str_strm >> tmp) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
} 예시
또 다른 방법은 getline 함수 −
를 사용하여 문자열을 분할하는 사용자 지정 구분 기호를 제공하는 것입니다.#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
std::stringstream str_strm("Hello from the dark side");
std::string tmp;
vector<string> words;
char delim = ' '; // Ddefine the delimiter to split by
while (std::getline(str_strm, tmp, delim)) {
// Provide proper checks here for tmp like if empty
// Also strip down symbols like !, ., ?, etc.
// Finally push it.
words.push_back(tmp);
}
}