修改字符串数组中的字符串

Modifying strings in an Array of strings

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

我有一个字符串数组,我想随意修改它的元素。这是代码:

char pieces[9][4] = { "   ", " o ", " a ", "   ", "   ", "   ", " b ", "   ", "   " };
pieces[2] = { " x " };

据我所知,pieces[] 中的元素是字符串文字,因此无法更改(我不确定为什么会这样(。也许可以使用std::string或向量来解决。但是,我想知道是否可以使用字符串数组来完成这种操作或非常相似的操作。可以只使用字符串数组来完成这样的事情吗?

在你的特定情况下,看起来你总是有一些被空格包围的字符,所以你可以简单地做pieces[2][1] = 'x';来修改那个元素。然而。。。

您正确地假设这可以通过std::stringstd::vector变得更容易,但由于我们已经知道大小,因此std::array在这里可能会更好:

std::array<std::string, 9> pieces = { "   ", " o ", " a ", "   ", "   ", "   ", " b ", "   ", "   " };
pieces[2] = " x ";

您可能会注意到下标运算符仍然适用于std::array。这意味着即使您切换到std::array的,您甚至可能不必在其他代码中更改太多(只需处理处理 c 字符串的部分来处理std::strings

您可以使用strcpy();

请参阅以下示例代码。在此处查看工作代码:

int main(void) 
{
char pieces[9][4] = { "   ", " o ", " a ", "   ", "   ", "   ", " b ", "   ", "   " };
printf("At point 1: %sn",pieces[2]);
strcpy(pieces[2]," x ");
printf("At point 2: %s",pieces[2]);
return 0;
}

输出:

At point 1:  a 
At point 2:  x 

pieces[2][0] = ' ';
pieces[2][1] = 'x';
pieces[2][2] = ' ';
pieces[2][3] = '';

做你想做的事?

首先,使用像pieces[2] = { " x " };这样的大括号是初始化的方式,所以你不能这样做。

其次,pieces[2]是一个字符数组,因此它是不可修改的 l 值。

您可以逐个元素或使用strcpy()函数更改其内容。

只是为了总结不同用户给出的不同解决方案,选项是:

  • 一次修改一个 char 元素。示例:片段[2][1] = 'x'

  • 使用 strcpy((。示例:strcpy(pieces[2]," x "(

  • 另一种类型:std::array,std:
  • :string,std:vector