c++ - 将数据的某些部分从 const char * 数组复制到另一个 const char * 数组

标签 c++ string visual-c++

我能够在循环中将一些数据从 char 数组复制到另一个 char 数组。例如,我想将 char 数组的每 2 个字符提取并显示到 b 中。但它不适用于 const char *。谁能告诉我为什么它不能与 const char * 一起使用。实际上,我需要用 const char* 来做到这一点。

char array[] = "HelloRamBilasj";

cout << "total length of array buffer:" << strlen(array) << endl << endl;
int totalGoLength= strlen(array)/2 ; //divide by number of elements you want to display in one loop

cout << "required length of alice buffer:" << totalGoLength << endl << endl;

int oneGoCount=1;
int start=0;//starting index to copy
int next=2;//end index to copy

while( oneGoCount <= totalGoLength) {

    char *b = new char[100];
    // now copy the elemet into b.
    std::copy(array+start, array+next, b);

    for (int i = 0; i < 2; ++i){
        cout<< "the value of b is"<<b[i]<<endl;

    }
    cout<<endl<<endl;

    delete [] b;//erase the contents of b.
    start=start+2;//increment the next index
    next=next+2;//increment the next index

    oneGoCount=oneGoCount+1;

}//end of while

最佳答案

您不能更改 const char* 指向的数据,因为它指向的数据是 const

关于c++ - 将数据的某些部分从 const char * 数组复制到另一个 const char * 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25933263/

相关文章:

c++ - 没有明显目标的 std::cout 留在发布的代码中是一件坏事吗?

c++ - std::hash_set 中定义的 stdext::hash_value() 的性能

c++ - 在泛型类的每个实例化中增加编译时变量

c++ - 使用链表制作模板类

c++ - 如何将 M x N 矩阵原地旋转 180 度?

c++ - 如何修复 "use of class template requires template argument list"

Python:连接字符串列表if else oneliner

c - scanf 字符串困惑

javascript - 如何从字符串中删除最后一个 '[]'?

c++ - 警告 C4996 : This function or variable may be unsafe -- compared to GCC on POSIX