在C 中可能是字符串数组

is string array possible in c++?

本文关键字:字符串 数组      更新时间:2023-10-16

据我所知,在C string中本身就是char的数组。

所以我的问题是:
是否可以在C ?

中有一个字符串数组

如果是,请让我知道声明/处理它的方法。

当然是:

// Requires <string> and <vector> includes
std::vector<std::string> foo = {"this", "is", "a", "string", "array"};

// Requires <string> and <array> includes
std::array<std::string, 3> foo = {"if", "you", "must"};

作为经验法则,始终使用使用std::vector,除非您能想到一个很好的理由不。

在现代C 中,我们尽量不要将字符串视为字符数组。标准库中的一些高级工具提供了我们需要的间接水平。

五个字符串的数组:

std::array<std::string, 5> = {"init.", "generously", "provided", "by", "Bathsheba" };

字符串的动态阵列:

std::vector<std::string> = { "as", "much", "strings", "as", "one", "wants" };

请参阅他们的相关文档:

  • std::string
  • std::array
  • std::vector

字符串是一种类型。与任何其他类型一样,可以在C 中定义一系列字符串:

std::string myarray[] = {"Hello", "World", "Lorem"};

或:

std::vector<std::string> myarray = {"Hello", "World", "Lorem"};

或:

std::array<std::string, 3> myarray = {"Hello", "World", "Lorem"};

请确保包括<string>和其他适当的标头。这是STD :: String类模板的更多信息。

这是您想要的:

#include <string>
// ...
std::string str_array[] = {"some", "strings", "in", "the", "array"};

但实际上您最好使用其他答案中所示的std::arraystd::vector