可能重复:
如何在C++中拆分字符串?
我需要用单个空格分割一个字符串并将其存储到一个字符串数组中.我可以使用istringstream实现这一点,但我无法实现的是:
我希望每个空格都能终止当前的单词.因此,如果连续有两个空格,则我的数组中的一个元素应为空白.
例如:
(下划线表示空格)
This_is_a_string.
gets split into:
A[0] = This
A[1] = is
A[2] = a
A[3] = string.
This__is_a_string.
gets split into:
A[0] = This
A[1] = ""
A[2] = is
A[3] = a
A[4] = string.
Run Code Online (Sandbox Code Playgroud)
我该如何实现呢?
Ise*_*ria 27
如果严格一个空格字符是分隔符,则可能std::getline有效.
例如:
int main() {
using namespace std;
istringstream iss("This is a string");
string s;
while ( getline( iss, s, ' ' ) ) {
printf( "`%s'\n", s.c_str() );
}
}
Run Code Online (Sandbox Code Playgroud)
Bal*_*arq 26
你甚至可以开发自己的分割功能(我知道,很老式):
size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
size_t pos = txt.find( ch );
size_t initialPos = 0;
strs.clear();
// Decompose statement
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
// Add the last one
strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );
return strs.size();
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要使用vector <string>作为参数调用它:
int main()
{
std::vector<std::string> v;
split( "This is a test", v, ' ' );
dump( cout, v );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
你可以使用boost吗?
samm$ cat split.cc
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <string>
#include <vector>
int
main()
{
std::string split_me( "hello world how are you" );
typedef std::vector<std::string> Tokens;
Tokens tokens;
boost::split( tokens, split_me, boost::is_any_of(" ") );
std::cout << tokens.size() << " tokens" << std::endl;
BOOST_FOREACH( const std::string& i, tokens ) {
std::cout << "'" << i << "'" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
样本执行:
samm$ ./a.out
8 tokens
'hello'
'world'
''
'how'
'are'
''
''
'you'
samm$
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
169541 次 |
| 最近记录: |