Replace lowercase characters with star

2019-06-14 02:44发布

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);

    }

2条回答
Fickle 薄情
2楼-- · 2019-06-14 03:23

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());
查看更多
孤傲高冷的网名
3楼-- · 2019-06-14 03:40

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"
查看更多
登录 后发表回答