假设我有一串数字
"1 2 3 4 5 6"
Run Code Online (Sandbox Code Playgroud)
我想分割此字符串并将每个数字放入向量中的另一个插槽中。最好的方法是什么
使用istringstream将字符串称为流,并使用>>运算符获取数字。如果字符串包含换行符和制表符,它也将起作用。这是一个例子:
#include <vector>
#include <sstream> // for istringstream
#include <iostream> // for cout
using namespace std; // I like using vector instead of std::vector
int main()
{
char *s = "1 2 3 4 5";
istringstream s2(s);
vector<int> v;
int tmp;
while (s2 >> tmp) {
v.push_back(tmp);
}
// print the vector
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
std::vector<std::string> StringToVector(std::string const& str, char const delimiter);
int main(){
std::string str{"1 2 3 4 5 6 "};
std::vector<std::string> vec{StringToVector(str, ' ')};
//print the vector
for(std::string const& item : vec){
std::cout << "[" << item << "]";
}
return EXIT_SUCCESS;
}
std::vector<std::string> StringToVector(std::string const& str, char const delimiter){
std::vector<std::string> vec;
std::string element;
//we are going to loop through each character of the string slowly building an element string.
//whenever we hit a delimiter, we will push the element into the vector, and clear it to get ready for the next element
for_each(begin(str),end(str),[&](char const ch){
if(ch!=delimiter){
element+=ch;
}
else{
if (element.length()>0){
vec.push_back(element);
element.clear();
}
}
});
//push in the last element if the string does not end with the delimiter
if (element.length()>0){
vec.push_back(element);
}
return vec;
}
Run Code Online (Sandbox Code Playgroud)
g++ -std=c++0x -o main main.cpp
这样做的优点是永远不会将空字符串推入向量中。
您还可以选择您想要的分隔符。
也许你可以写一些其他的:一个用于字符向量或者分隔符可能是一个字符串?:)
祝你好运!