Igo*_*gor 6 c++ arrays string vector
我正在尝试编写一个带字符串的函数,并分割每X个字符:
std::vector<std::string> DIFSplitStringByNumber(std::string s, int l)
{
const char *c = s.c_str();
char buffer[l];
std::vector<std::string> entries;
entries.reserve(int(s.length() / l) + 1);
int d = 0;
for(int i = 0; i < s.length() - 1;)
{
if(d != l)
{
buffer[d] = c[i];
d++;
i++;
}
else
{
entries.push_back(std::string(buffer, l));
//Clear array
memset(buffer, 0, l);
d = 0;
}
}
return entries;
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我打电话DIFSplitStringByNumber("hello!", 2),我应该得到一个包含以下内容的向量:
[0] he
[1] ll
[2] o!
Run Code Online (Sandbox Code Playgroud)
但是,它似乎只得到前两个结果(向量大小为2),当我做类似的事情时DIFSplitStringByNumber("hello", 2),它崩溃了,大概是因为它试图访问一个不存在的数组索引(它需要6个字符,但是只有5).有更简单的方法吗?
算法的核心实际上归结为以下两行.
for (size_t i = 0; i < s.size(); i += l)
res.push_back(s.substr(i, l));
Run Code Online (Sandbox Code Playgroud)
此外,您应该通过const引用传递字符串.
这会将字符串拆分为向量。如果分割数不是偶数,它会将额外的字符添加到末尾。
std::vector<std::string> Split(const std::string& str, int splitLength)
{
int NumSubstrings = str.length() / splitLength;
std::vector<std::string> ret;
for (auto i = 0; i < NumSubstrings; i++)
{
ret.push_back(str.substr(i * splitLength, splitLength));
}
// If there are leftover characters, create a shorter item at the end.
if (str.length() % splitLength != 0)
{
ret.push_back(str.substr(splitLength * NumSubstrings));
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)