温馨提示×

c++字符串数组赋值的方法是什么

c++
小亿
95
2024-04-19 18:22:16
栏目: 编程语言

在C++中,可以使用以下方法来给字符串数组赋值:

  1. 使用下标赋值:直接通过下标索引来赋值字符串数组的每个元素。
#include <iostream>
#include <string>

int main() {
    std::string arr[3];

    arr[0] = "Hello";
    arr[1] = "World";
    arr[2] = "C++";

    for (int i = 0; i < 3; i++) {
        std::cout << arr[i] << std::endl;
    }

    return 0;
}
  1. 使用strcpy函数:利用strcpy函数将字符串赋值给数组中的元素。
#include <iostream>
#include <cstring>

int main() {
    char arr[3][10];

    strcpy(arr[0], "Hello");
    strcpy(arr[1], "World");
    strcpy(arr[2], "C++");

    for (int i = 0; i < 3; i++) {
        std::cout << arr[i] << std::endl;
    }

    return 0;
}
  1. 使用std::vector:使用std::vector来管理字符串数组。
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> arr;

    arr.push_back("Hello");
    arr.push_back("World");
    arr.push_back("C++");

    for (int i = 0; i < arr.size(); i++) {
        std::cout << arr[i] << std::endl;
    }

    return 0;
}

以上是几种常见的给字符串数组赋值的方法,选择适合自己需求的方法来操作字符串数组。

0