0

i wrote a code for replacing lowercase characters to *. but it does not work. where is the problem?

   private void CharacterReplacement()
    {
        Console.WriteLine("Enter a string to replacement : ");
        string TargetString = Console.ReadLine();
        string MainString = TargetString;
        for (int i = 0; i < TargetString.Length; i++)
        {
            if (char.IsLower(TargetString[i]))
            {
                TargetString.Replace(TargetString[i], '*');
            }
        }
        Console.WriteLine("The string {0} has converted to {1}", MainString, TargetString);

    }
steinar
  • 9,383
  • 1
  • 23
  • 37
Shahin
  • 12,543
  • 39
  • 127
  • 205

2 Answers2

5

Replace() returns a new string, so you need to re-assign it to TargetString:

TargetString =  TargetString.Replace(TargetString[i], '*');

Another way to express your intend would be with Linq - not sure which I like better, this avoids all the temporary strings but has other overhead:

TargetString = new string(TargetString.Select(c => char.IsLower(c) ? '*' : c)
                                     .ToArray());
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
3

You can of course write this in one short line by using a regular expression:

string output = Regex.Replace("ABCdef123", "[a-z]", "*"); // output = "ABC***123"

Improved version based on Arto's comment, that handles all lowercase unicode characters:

string output = Regex.Replace("ABCdefëï123", "\p{Ll}", "*"); // output = "ABC*****123"
Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56
  • 1
    Actually \p{Ll} is closer to the IsLower, since both use Unicode category LowerCase. (Try Ää12; ä is lowercase of Ä) – Arto Viitanen Apr 04 '11 at 05:14