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++ 实现有什么不同吗?
如果numReplace在 [0,9] 范围内,你可以这样做:-
testArray[0] = numReplace + '0';
如果numReplace在 [0,9] 之外,你需要
numReplace为等效字符串参考:在 c 中用另一个字符串替换一部分字符串的最佳方法以及其他相关帖子
另外,由于这是 C++ 代码,您可能会考虑使用std::string,这里的替换、数字到字符串的转换等要简单得多。