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

标签 c++ arrays char int

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

#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/

相关文章:

c++ - 使用特定的 MFC 版本构建 C++ DLL

c++ - 输出声明堆在释放后被修改,但没有添加到堆中

C++如何在给定范围内添加数组中的数字?

c - 在 C 中传递结构的一部分

c++ - 组类类型

javascript - 在对象数组中添加数字

c++ - 将数组类切换为模板时出现错误

c# - 为什么值为 128 的字符是空字符串而不是欧元符号 €

c - 切换字符串c语言

c++ - 将可变模板参数传递给可变函数