0

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.

Mohammed Alawneh
  • 306
  • 9
  • 22

3 Answers3

2

char is already ASCII, but to do math on it, you need a number.

So:

  1. Cast to int
  2. Do your math (subtract 1)
  3. 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:

  • This won't work with 'a' or 'A'
  • Strings are immutable you can't just change a character. You can create a new string with the replaced character, but that isn't technically the same thing.
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • Technically, strings are immutable, however, you could probably create an `unsafe` function that manipulates the string using pointers. However, this is definitely NOT a good idea. – Icemanind Oct 06 '14 at 16:55
  • @icemanind Yes, you can do a lot more when you let pointers back in. As you say *not* a good idea, especially for someone new. – BradleyDotNET Oct 06 '14 at 16:56
0

Replace return string to object, but not change values on it. The solution's:

s = s.Replace(s[StringSize-1], the previous char);
Marek Woźniak
  • 1,766
  • 16
  • 34
0
    var str = "abcd";
    for (int i = 0; i < str.Length; i++)
    {
        str = str.Replace(str[i], (char)((byte)str[i] - 1));
    }
vikas
  • 931
  • 6
  • 11