C/C++ 문자열의 단어를 반복하는 우아한 방법은 없습니다. 가장 읽기 쉬운 방법이 어떤 사람에게는 가장 우아하고 어떤 사람에게는 가장 성능이 좋은 방법이라고 할 수 있습니다. 이를 달성하는 데 사용할 수 있는 2가지 방법을 나열했습니다. 첫 번째 방법은 stringstream을 사용하여 공백으로 구분된 단어를 읽는 것입니다. 이것은 약간 제한적이지만 적절한 검사를 제공하면 작업을 상당히 잘 수행합니다. 예를 들어>
예시 코드
#include <iostream>
#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);
}
for(int i = 0; i<words.size(); i++)
cout << words[i] << endl;
} 출력
Hello from the dark side