我有一个包含 1000 个字符的字符串。我想将这个字符串拆分为一个字符串数组,每个字符串包含 5 个字符。代码是:
int main()
{
string myarray[200];
int k = 0;
string num = "a string with 1000 characters";
while(!num.empty())
{
strncpy(myarray[k],num.c_str(),5);
num.erase(0,5);
k++;
}
}
这段代码给出了这个错误:
cannot convert 'std::string {aka std::basic_string}' to 'char*' for argument '1' to 'char* strncpy(char*, const char*, size_t)'|
我尝试了没有 .c_str() 的代码,结果是一样的。 我怎样才能解决这个问题?谢谢。
最佳答案
函数strncpy当您将 string
传递给它时,期望第一个参数是 char*
。编译器会提示它无法将 std::string
转换为 char*
:
char *strncpy( char *dest, const char *src, std::size_t count );
更好用std::vector并调用std::string::substr :
#include <string>
#include <vector>
std::string num("a string with 1000 characters");
std::vector<std::string> myarray;
myarray.reserve(200);
for (int i=0; i<num.size(); i+=5)
{
myarray.push_back(num.substr(i, 5));
}
关于c++ - 在 C++ 中将字符串划分为更小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18427494/