1

Im trying to replace every 2nd character of user entered text to a underscore. I have iterated through a character array but when I try to change a specific character using an index it says "Cannot implicitly convert type 'String' to 'Char'.

What am I doing wrong here? Thanks.

Char[] secondChar = enteredString.ToCharArray();
for (int i = 1; i < secondChar.Length; i += 2)
{
    secondChar[i] = "_";
}
Console.WriteLine(secondChar);
4
  • 3
    "_" is a string. '_' is a char. Commented Apr 22, 2018 at 22:23
  • @PatrickArtner, Im trying to replace the 2nd character, OP intentionaly uses index 1 Commented Apr 22, 2018 at 22:24
  • Yeah, starting at 1 was intentional. I don't know how I blanked on the double quotes, thanks. Commented Apr 22, 2018 at 22:29
  • If you want to overkill it, use System.Linq: var replaced = string.Join("",enteredString.Select( (ch,idx) => idx%2==1 ? '_': ch)); Commented Apr 22, 2018 at 22:35

1 Answer 1

3

You are using double quotes which indicates a string. Use single quotes instead to indicate char.

secondChar[i] = '_';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.