C++ 按单个空格拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5888022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string by single spaces
提问by xbonez
Possible Duplicate:
How to split a string in C++?
可能的重复:
如何在 C++ 中拆分字符串?
I need to split a string by single spaces and store it into an array of strings. I can achieve this using a istringstream, but what I am not being able to achieve is this:
我需要用单个空格分割一个字符串并将其存储到一个字符串数组中。我可以使用 istringstream 实现这一点,但我无法实现的是:
I want every space to terminate the current word. So, if there are two spaces consecutively, one element of my array should be blank.
我希望每个空格都终止当前单词。所以,如果连续有两个空格,我的数组的一个元素应该是空白的。
For example:
例如:
(underscore denotes space)
(下划线表示空格)
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.
How can I implement this?
我该如何实施?
采纳答案by Baltasarq
You can even develop your own split function (I know, little old-fashioned):
您甚至可以开发自己的拆分功能(我知道,有点老式):
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();
}
Then you just need to invoke it with a vector<string> as argument:
然后你只需要使用 vector<string> 作为参数调用它:
int main()
{
std::vector<std::string> v;
split( "This is a test", v, ' ' );
dump( cout, v );
return 0;
}
Find the code for splitting a string in IDEone.
Hope this helps.
希望这可以帮助。
回答by Ise Wisteria
If strictly one space character is the delimiter,
probably std::getline
will be valid.
For example:
如果严格以一个空格字符作为分隔符,则可能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() );
}
}
回答by Sam Miller
Can you use 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;
}
}
sample execution:
示例执行:
samm$ ./a.out
8 tokens
'hello'
'world'
''
'how'
'are'
''
''
'you'
samm$
回答by Rob?
If you are averse to boost, you can use regular old operator>>
, along with std::noskipws
:
如果你不喜欢提升,你可以使用常规的 old operator>>
,以及std::noskipws
:
EDIT: updates after testing.
编辑:测试后更新。
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
void split(const std::string& str, std::vector<std::string>& v) {
std::stringstream ss(str);
ss >> std::noskipws;
std::string field;
char ws_delim;
while(1) {
if( ss >> field )
v.push_back(field);
else if (ss.eof())
break;
else
v.push_back(std::string());
ss.clear();
ss >> ws_delim;
}
}
int main() {
std::vector<std::string> v;
split("hello world how are you", v);
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "-"));
std::cout << "\n";
}
回答by Cubbi
If you are not averse to boost, boost.tokenizer is flexible enough to solve this
如果你不反对 boost,boost.tokenizer 足够灵活来解决这个问题
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
void split_and_show(const std::string s)
{
boost::char_separator<char> sep(" ", "", boost::keep_empty_tokens);
boost::tokenizer<boost::char_separator<char> > tok(s, sep);
for(auto i = tok.begin(); i!=tok.end(); ++i)
std::cout << '"' << *i << "\"\n";
}
int main()
{
split_and_show("This is a string");
split_and_show("This is a string");
}
test: https://ideone.com/mN2sR
回答by TurqMage
You could also just use the old fashion 'strtok'
你也可以只使用旧时尚的“strtok”
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Its a bit wonky but doesn't involve using boost (not that boost is a bad thing).
它有点不稳定,但不涉及使用提升(并不是说提升是一件坏事)。
You basically call strtok with the string you want to split and the delimiter (in this case a space) and it will return you a char*.
您基本上使用要拆分的字符串和分隔符(在本例中为空格)调用 strtok ,它将返回一个 char* 。
From the link:
从链接:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
回答by TurqMage
You could used simple strtok() function (*)From here. Note that tokens are created on delimiters
您可以使用简单的 strtok() 函数 (*)从这里开始。请注意,令牌是在分隔符上创建的
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This is a string";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}