【问题标题】:How to replace certain items in a char array with an integer in C++?如何用 C++ 中的整数替换 char 数组中的某些项目?
【发布时间】:2014-04-06 18:35:32
【问题描述】:

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

#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++ 中执行它有什么不同?

【问题讨论】:

  • 字符常量'2'的整数值和整数常量2不一样。

标签: c++ arrays char int


【解决方案1】:

如果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,这里的替换、数字到字符串的转换等要简单得多。

【讨论】:

  • 这完全有效。但是,请问如果超出该范围该怎么办?...但是回想一下...一个字符数组只适合一个字符吗?...它不能适合任何超过 1 位的数字。
  • 查看 std::string,它具有任意子字符串长度的替换方法。此外,还有方便的转换,从二进制数到 std::ostringstream,这将为您提供要插入其他字符串的字符串。
【解决方案2】:

您应该在这里查看 ASCII 表:http://www.asciitable.com/ 这很舒服 - 总是在 Decimal 列中查找您正在使用的 ASCII 值。 在该行中:TestArray[0] = (int)numreplace; 实际上,您已将十进制 ASCII 值为 2 的字符放在第一个位置。numReplace + '0' 可以做到这一点:) 关于 C/C++ 问题,在字符和整数方面都是相同的...... 你应该寻找你的号码开始和结束。 您应该创建一个如下所示的循环:

int temp = 0, numberLen, i, j, isOk = 1, isOk2 = 1, from, to, num;
char str[] = "asd 12983 asd";//will be added 1 to.
char *nstr;
for(i = 0 ; i < strlen(str) && isOk ; i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
from = i;
for(j = i ; j < strlen(str) && isOk2)
{
if(str[j] < '0' || str[j] > '9')//not a number;
{
to=j-1;
isOk2 = 0;
}
}
isOk = 0; //for the loop to stop.
}
}
numberLen = to-from+1;
nstr = malloc(sizeof(char)*numberLen);//creating a string with the length of the number.
for(i = from ; i <= to ; i++)
{
nstr[i-from] = str[i];
}
/*nstr now contains the number*/
num = atoi(numstr);
num++; //adding - we wanted to have the number+1 in string.
itoa(num, nstr, 10);//putting num into nstr
for(i = from ; i <= to ; i++)
{
str[i] = nstr[i-from];
}
/*Now the string will contain "asd 12984 asd"*/

顺便说一句,最有效的方法可能是寻找最后一个数字并将其值加 1(再次是 ASCII),因为 ASCII 中的数字彼此跟随 - '0'=48, '1'= 49 以此类推。但我只是向您展示了如何将它们视为数字并将它们视为整数等。希望它有所帮助:)

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 2019-03-04
    • 1970-01-01
    • 2011-08-20
    • 2014-03-23
    • 1970-01-01
    • 2016-02-27
    • 2018-12-18
    • 2019-07-15
    相关资源
    最近更新 更多