Mohammed Alawneh
Mohammed Alawneh

Reputation: 306

how to change a char to the previous one of it (alphabetically) in string using c#?

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

Answers (3)

vikas
vikas

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

Marek Woźniak
Marek Woźniak

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

BradleyDotNET
BradleyDotNET

Reputation: 61379

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.

Upvotes: 2

Related Questions