如何使用分隔符将字符串拆分为数组? [英] How can I split a string by a delimiter into an array?
问题描述
我是编程的新人。我一直在尝试在C ++中编写一个函数,它将一个字符串的内容展开为给定参数的字符串数组,例如:
I am new to programming. I have been trying to write a function in C++ that explodes the contents of a string into a string array at a given parameter, example:
string str = "___this_ is__ th_e str__ing we__ will use__";
应返回字符串数组:
cout << stringArray[0]; // 'this'
cout << stringArray[1]; // ' is'
cout << stringArray[2]; // ' th'
cout << stringArray[3]; // 'e str'
cout << stringArray[4]; // 'ing we'
cout << stringArray[5]; // ' will use'
我可以将字符串标记为正确的,但对我来说最难的部分是如何在指定当前字符串toke之前指定stringArray中的元素数量,以及如何从函数返回stringArray。
I can tokenize the string just fine, but the hardest part for me is how can i specify the number of elements in stringArray before assigning it the current string toke and also how to return stringArray from the function.
有人会告诉我如何写函数?
Would someone show me how to write the function?
Edit1:我不一定需要的结果是在字符串数组只是任何容器,我可以调用作为一个常规变量
I don't necessarily need the results to been in string array just any container that i can call as a regular variable with some sort of indexing.
推荐答案
这是我第一次尝试使用向量和字符串:
Here's my first attempt at this using vectors and strings:
vector<string> explode(const string& str, const char& ch) {
string next;
vector<string> result;
// For each character in the string
for (string::const_iterator it = str.begin(); it != str.end(); it++) {
// If we've hit the terminal character
if (*it == ch) {
// If we have some characters accumulated
if (!next.empty()) {
// Add them to the result vector
result.push_back(next);
next.clear();
}
} else {
// Accumulate the next character into the sequence
next += *it;
}
}
if (!next.empty())
result.push_back(next);
return result;
}
希望这给你一些如何去做的想法。在你的示例字符串,它返回正确的结果与这个测试代码:
Hopefully this gives you some sort of idea of how to go about this. On your example string it returns the correct results with this test code:
int main (int, char const **) {
std::string blah = "___this_ is__ th_e str__ing we__ will use__";
std::vector<std::string> result = explode(blah, '_');
for (size_t i = 0; i < result.size(); i++) {
cout << "\"" << result[i] << "\"" << endl;
}
return 0;
}
这篇关于如何使用分隔符将字符串拆分为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!