首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

迭代字符串并在C++中填充数组

在C++中,迭代字符串并填充数组可以通过以下方式实现:

代码语言:txt
复制
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    char arr[10];

    int i = 0;
    for (char c : str) {
        arr[i] = c;
        i++;
    }

    // 填充剩余的数组元素为'\0'
    for (; i < 10; i++) {
        arr[i] = '\0';
    }

    // 打印填充后的数组
    for (char c : arr) {
        std::cout << c;
    }

    return 0;
}

上述代码中,我们首先定义了一个字符串str和一个字符数组arr。然后,我们使用范围for循环迭代字符串中的每个字符,并将其依次填充到数组中。最后,我们使用另一个循环将剩余的数组元素填充为\0,以确保数组的所有元素都被正确初始化。最后,我们使用范围for循环打印填充后的数组。

这种方法适用于任何字符串,并且可以根据需要调整数组的大小。在实际应用中,您可以根据具体的需求进行修改和优化。

腾讯云相关产品和产品介绍链接地址:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版:https://cloud.tencent.com/product/cdb_mysql
  • 云原生容器服务(TKE):https://cloud.tencent.com/product/tke
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 物联网开发平台(IoT Explorer):https://cloud.tencent.com/product/iothub
  • 移动推送服务(信鸽):https://cloud.tencent.com/product/tpns
  • 对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯区块链服务(Tencent Blockchain):https://cloud.tencent.com/product/tbc
  • 腾讯云元宇宙(Tencent Cloud Metaverse):https://cloud.tencent.com/solution/metaverse
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券