c++ - 在 C++ 中将字符串划分为更小的字符串

标签 c++ string parsing

我有一个包含 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/

相关文章:

c++ - 我应该删除 move 构造函数和智能指针的 move 分配吗?

c++ - 多纹理 OpenGL GLUT C++

c++ - 获取 Apache Avro 通用记录字段的名称?

c - 如何在调用 atoi 之前将指针设置为 NULL

java - java : 的 JSON 解析器错误

c++ - 如何将对象的指针写入文件?

string - 如何替换Go中字符串中特定索引处的字母?

java - 如何在 Java 中比较字符串?

c++ - 为二进制结构化数据生成解析器;元编程或外部脚本?

linux - 解析 iostat 输出