std::vector<char*> Split(std::string input) {
std::vector<char*> ret;
std::istringstream f(input);
std::string s;
while (getline(f, s, ' ')) {
ret.push_back((char*)s.c_str());
}
return ret;
}
这个函数的意思是取一个字符串并把每个单词放到一个向量中。 但是假设我将ls-l
作为字符串。 它应该返回一个包含两个元素ls
和-l
的向量。 相反,它返回一个包含两个元素-L
和L
的向量。 谁能帮我拿一下这个吗?
复制指针并不意味着复制被指向的东西。
看来你得抄袭这些字符串。
#include <cstring> // for strlen() and strcpy()
std::vector<char*> Split(std::string input) {
std::vector<char*> ret;
std::istringstream f(input);
std::string s;
while (getline(f, s, ' ')) {
char* buf = new char[strlen(s.c_str()) + 1]; // +1 for terminating null-character
strcpy(buf, s.c_str());
ret.push_back(buf);
}
return ret;
}
您正在向量中存储指向字符串的指针,但字符串s
在函数退出时被破坏。 因此您正在存储指向已删除对象的指针。
使用字符串而不是指针。 字符串很容易正确复制,不像指针。 试试这个
std::vector<std::string> Split(std::string input) {
std::vector<std::string> ret;
std::istringstream f(input);
std::string s;
while (getline(f, s, ' ')) {
ret.push_back(s);
}
return ret;
}
您从另外两个答案中得到了您的答案,但我有另一种方法可以拆分字符串(称为字符串标记化
):
std::vector<std::string> split(std::string text) {
std::vector<std::string> words;
std::string temp{};
for (int i=0; i < text.size(); ++i) {
if (text[i] != ' ') {
temp.push_back(text[i]);
if (i == text.size()-1) {
words.push_back(temp);
}
}
else if (temp.size() != 0) {
words.push_back(temp);
temp.clear();
}
}
return words;
}