Question

Below is an example code that is not working the way I want.

#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;
}

In a string with characters and integers, how do you go about replacing numbers? And when implementing this, is it different between doing it in C and C++?

Était-ce utile?

La solution

If numReplace will be in range [0,9] you can do :-

testArray[0] = numReplace + '0';


If numReplace is outside [0,9] you need to

  • a) convert numReplace into string equivalent
  • b) code a function to replace a part of string by another evaluated in (a)

Ref: Best way to replace a part of string by another in c and other relevant post on SO

Also, since this is C++ code, you might consider using std::string, here replacement, number to string conversion, etc are much simpler.

Autres conseils

You should look over the ASCII table over here: http://www.asciitable.com/ It's very comfortable - always look on the Decimal column for the ASCII value you're using. In the line: TestArray[0] = (int)numreplace; You've actually put in the first spot the character with the decimal ASCII value of 2. numReplace + '0' could do the trick :) About the C/C++ question, it is the same in both and about the characters and integers... You should look for your number start and ending. You should make a loop that'll look like this:

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"*/

By the way, the most efficient way would probably be just looking for the last digit and add 1 to it's value (ASCII again) as the numbers in ASCII are following each other - '0'=48, '1'=49 and so on. But I just showed you how to treat them as numbers and work with them as integers and so. Hope it helped :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top