Reputation: 306
hello i am searching for a good approach to change a single char in a string to the previous char of it . i mean if i have this string = "abcd" i want to change the 'd' char to 'c' ? how to change the char to to the one before it (alphabetically) ?
i want to use the approach here:
int StringSize=0;
string s=" ";
s = Console.ReadLine();
StringSize = s.Length;
s.Replace(s[StringSize-1],the previous char);
i want to change the char s [StringSize-1] to the previous char of it.
I've tried to do this depending on the ASCII code of the character but i did't find a method to convert form char to ASCII.
Upvotes: 0
Views: 379
Reputation: 939
var str = "abcd";
for (int i = 0; i < str.Length; i++)
{
str = str.Replace(str[i], (char)((byte)str[i] - 1));
}
Upvotes: 0
Reputation: 1786
Replace return string to object, but not change values on it. The solution's:
s = s.Replace(s[StringSize-1], the previous char);
Upvotes: 0
Reputation: 61379
char
is already ASCII, but to do math on it, you need a number.
So:
int
Cast back to char
char newChar = (char)((int)oldChar - 1);
Or in your code:
s = s.Replace(s[StringSize-1], (char)((int)s[StringSize-1] - 1));
Caveats:
Upvotes: 2