下面是一个示例代码,它没有按我想要的方式工作。
#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;
}
在包含字符和整数的字符串中,如何替换数字?在实现这个时,用 C 和 C++ 做它有什么不同吗?
最佳答案
如果 numReplace
将在 [0,9] 范围内,您可以这样做:-
testArray[0] = numReplace + '0';
如果 numReplace
在 [0,9] 之外你需要
- a) 将
numReplace
转换成等价的字符串 - b) 编写一个函数,用 (a) 中评估的另一个字符串替换字符串的一部分
引用:Best way to replace a part of string by another in c和 SO 上的其他相关帖子
此外,由于这是 C++ 代码,您可以考虑使用 std::string
,这里替换、数字到字符串的转换等要简单得多。
关于c++ - 如何用 C++ 中的整数替换 char 数组中的某些项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898208/