C++에서는 문자열을 자르려면 어떻게 하나요?
조회수 9693회
자바에서는 밑에 같이 쓸 수 있었는데 C++에서는 좀 쉬운 방법 없나요?
String str = "The quick brown fox";
String[] results = str.split(" ");
1 답변
-
1. Boost tokenizer사용
/*c++11이상*/ #include <iostream> #include <string> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; int main(int, char**) { string text = The quick brown fox"; //token할 스트링 char_separator<char> sep(", "); //token delim tokenizer<char_separator<char>> tokens(text, sep); for (const auto& t : tokens) { cout << t << "." << endl; } } /*c++11미만*/ #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; int main(int, char**) { string text = "token, test string"; //token할 스트링 char_separator<char> sep(", "); //token delim tokenizer< char_separator<char> > tokens(text, sep); BOOST_FOREACH (const string& t, tokens) { cout << t << "." << endl; } }
2. stringstream
std::string str = "The quick brown fox"; //token할 스트링 // string으로 부터 stringstream 생성 std::stringstream strstr(str); // 이터레이터를 써서 벡터에 공백을 제외하고 copy std::istream_iterator<std::string> it(strstr); std::istream_iterator<std::string> end; std::vector<std::string> results(it, end); // 출력 std::ostream_iterator<std::string> oit(std::cout); std::copy(results.begin(), results.end(), oit);
와 같이 쓰시면 됩니다.
댓글 입력