我是C ++的新手,我试图编写一些基本函数来了解其中的一些问题,因此我决定制作一个自定义函数,以在每次到达特定的定界符时将字符串拆分为标记。
我已经使其成功运行,但是由于我是新手,所以我想听听经验丰富的程序员提供的解决方案。这是我的代码:
vector<string> split(string const str, string const separator=" ") {
int str_len = str.length();
int sep_len = separator.length();
int current_index {0};
vector<string> strings {};
for(int i {0}; i < str_len; ++i) {
if(str.substr(i, sep_len) == separator) {
strings.push_back(str.substr(current_index, i-current_index));
current_index = i + sep_len;
}
}
strings.push_back(str.substr(current_index, str_len-current_index));
return strings;
}
我要说的一件事是,我不喜欢自己的表情
strings.push_back(str.substr(current_index, str_len-current_index));
在整个迭代之后获得字符串的最后一部分。我只是想不出任何其他方法。
答案 0 :(得分:1)
使用std::string::find()
在字符串中查找分隔符,这可能比检查该位置的子字符串是否与分隔符匹配的循环效率更高。一旦有了它,您就可以利用以下事实:如果找不到分隔符,find()
返回std::string::npos
,这是std::string::size_type
的最大可能值,因此只需将其传递给substr()
获取从当前位置到字符串末尾的所有内容。这样,您可以避免第二个push_back()
。
vector<string> split(string const &str, string const &separator=" ") {
string::size_type current_index {};
vector<string> strings;
while (true) {
auto separator_index = str.find(separator, current_index);
strings.push_back(str.substr(current_index, separator_index - current_index));
if (separator_index == str.npos)
break;
else
current_index = separator_index + separator.size();
}
return strings;
}
注意:确保您通过引用传递输入参数,以避免不必要的复制。