Vikash Tripathi Vikash Tripathi - 4 years ago 93
C# Question

Perform Select at odd positions in the string

I have to Replace the characters of input string at odd positions by next character in alphabet.

For Example

Input-

ABCD


output-
BBDD


I wanted something like this

string input = Console.ReadLine();
char[] k = input.ToCharArray().Select((val,i) =>(i%2==0) && (char)((int)val + 1)).ToArray();
string output=new string(k)

Answer Source

You are almost there, need to do little more to achieve the target. You have to notice the Following things and make those changes:

  • The condition i%2==0 determines whether the character need to be replaced or not, so you have to apply conditional operator(?:) here.
  • For valid condition you have to get the next character. For that you can try (char)((int)x + 1). this will first evaluates (int)x and gives the integer value of that particular character. then add 1 to it then get the corresponding character.
  • For false condition use the same character.
  • After these steps you will get a character array, you can use String.Join to make the output string from the character array

You can try something like this:

string input = "ABCD";
char[] k = input.Select((x, i) => i % 2 == 0 ? (char)((int)x + 1) : x).ToArray();
string output = String.Join("",k);

Working Example

Note the following things as well:

  • In this code we have not restricted characters, if your input contains Z the next value from the ASCII table will be assigned, that will be [.
  • If you want z to a and Z to A then you have to apply conditions for that.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download