如何将 char 数组(或其一部分)存储到 const char* 中?

问题描述 投票:0回答:1

我是 C++ 新手,在连接 const char* 和 char 数组时遇到问题。

首先我想问一个问题:const char* 和 std::string 一样吗?

直接解决我的问题,这就是我正在尝试的:

我有这个 10 大小的字符数组,其中包含从 a 到 j 的字母:

char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', j};

我想使用 const char* 存储这个数组(或其一部分)。但我无法进行串联,我认为有些人会这样想:

    const char* group_of_letters = "\0";
    
    for(int i = 0; i <= 9; i++){
        group_of_letters += my_array[i];
    }

我想使用 for 循环,因为我的实际项目需要它将该数组的定义间隔存储到 const char* 中 但我尝试过的任何方法都不起作用。

如果有帮助,我的完整代码将如下所示:

#include <iostream>

int main(){
    
    char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
    const char* group_of_letters = "\0";
    
    for(int i = 0; i <= 9; i++){
        group_of_letters += my_array[i];
    }
    
    std::cout << group_of_letters;
    
    return 0;
}

->使用 Dev C++ 5.11 - 06/08/2023

c++ arrays concatenation chararray
1个回答
0
投票

首先我想问一个问题:const char* 和 std::string 一样吗?

不,它们不一样,const char* 是指向 C 风格字符串中的字符序列的指针,而 std::string 是一个 C++ 类,它通过自动内存管理来管理和操作字符串。

不能使用 + 运算符连接 char* 数组。

const char* 不应该被改变,因为它是一个常量

在你的情况下,最好使用 std::string ,如下所示:

#include <iostream>
#include <string>

int main(){
    
    char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
    std::string group_of_letters;
    
    for(int i = 0; i <= 9; i++){
        group_of_letters += my_array[i];
    }
    
    std::cout << group_of_letters << std::endl;
    
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.