How to reverse only the alphabetic characters in a string, keeping other characters in place with C#

1 Answer

0 votes
using System;

class Program
{
    static string reverseOnlyAlphabeticCharacters(string s) {
        char[] chars = s.ToCharArray();
        int i = 0;
        int j = chars.Length - 1;

        while (i < j) {
            if (!char.IsLetter(chars[i])) {
                i++;
            }
            else if (!char.IsLetter(chars[j])) {
                j--;
            }
            else {
                char tmp = chars[i];
                chars[i] = chars[j];
                chars[j] = tmp;
                i++;
                j--;
            }
        }

        return new string(chars);
    }

    static void Main()
    {
        string s = "a1-bC2-dEf3-ghIj";

        Console.WriteLine(s);
        Console.WriteLine(reverseOnlyAlphabeticCharacters(s));
    }
}




/*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...