如何在 C++ 中用整数替换 char 数组中的某些项?

Arr*_*row 0 c++ arrays int char

下面是一个示例代码,它没有按照我想要的方式工作。

#include <iostream>

using namespace std;

int main()
{
char testArray[] = "1 test";

int numReplace = 2;
testArray[0] = (int)numReplace;
cout<< testArray<<endl; //output is "? test" I wanted it 2, not a '?' there
                        //I was trying different things and hoping (int) helped

testArray[0] = '2';
cout<<testArray<<endl;//"2 test" which is what I want, but it was hardcoded in
                      //Is there a way to do it based on a variable? 
return 0;
}
Run Code Online (Sandbox Code Playgroud)

在包含字符和整数的字符串中,如何替换数字?在实现这个时,用 C 和 C++ 实现有什么不同吗?

P0W*_*P0W 5

如果numReplace在 [0,9] 范围内,你可以这样做:-

testArray[0] = numReplace + '0';


如果numReplace在 [0,9] 之外,你需要

  • a) 转换numReplace为等效字符串
  • b) 编写一个函数,用 (a) 中计算的另一个函数替换字符串的一部分

参考:在 c 中用另一个字符串替换一部分字符串的最佳方法以及其他相关帖子

另外,由于这是 C++ 代码,您可能会考虑使用std::string,这里的替换、数字到字符串的转换等要简单得多。