views:

811

answers:

3

How can I count the number of characters within a string and create another string with the same number of characters but replace all of them with a single character such as "*"? Thank you.

+13  A: 
string newString = new string('*', oldString.Length);

Of course, it this is for displaying password equivalents, it might be better to use a fixed number of asterisks - the less clues the better. Of course, since you'd obviously be hashing the password (with salt) and storing just the hash, you couldn't know the actual length anyway ;-p

Marc Gravell
Works great. Thank you.
Nate Shoffner
A fixed number of asterisks makes no sense for a password input field. If you're going to give the user no feedback whatsoever, then you might as well not display anything at all.
Joren
+1  A: 

Another solution would be:

Console.Write(System.Text.RegularExpressions.Regex.Replace("test",".", "*"));
daxsorbito
From a performance perspective, it would be extremely unwise to create a Regex object for a purpose such as this. The above string methods would be more performant.
Qwerty
yah, I know but it seems the question didn't ask for any perfomance hit.
daxsorbito
Please back up "from a performance perspective ... unwise to create a Regex object". While it may not be an ideal solution here, this smells like a bad case of "premature optimization guessing".
pst
OK, happy to cater for your opinions re. "premature optimization guessing". However, my comment about not being a good idea to create a regex parser for this (over the other solutions) stands.
Qwerty
A: 
var message = "hello world" ;
var newMessage = new String('*', message.Length);
Qwerty
Use message.Length instead
Ahmed Said
agreed, silly typo. thx!
Qwerty