修改字符串数组中的字符串
Modifying strings in an Array of strings
我有一个字符串数组,我想随意修改它的元素。这是代码:
char pieces[9][4] = { " ", " o ", " a ", " ", " ", " ", " b ", " ", " " };
pieces[2] = { " x " };
据我所知,pieces[] 中的元素是字符串文字,因此无法更改(我不确定为什么会这样(。也许可以使用std::string或向量来解决。但是,我想知道是否可以使用字符串数组来完成这种操作或非常相似的操作。可以只使用字符串数组来完成这样的事情吗?
在你的特定情况下,看起来你总是有一些被空格包围的字符,所以你可以简单地做pieces[2][1] = 'x';
来修改那个元素。然而。。。
您正确地假设这可以通过std::string
和std::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
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组