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
2009-10-24 07:25:45
Works great. Thank you.
Nate Shoffner
2009-10-24 10:41:22
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
2009-10-29 22:34:20
+1
A:
Another solution would be:
Console.Write(System.Text.RegularExpressions.Regex.Replace("test",".", "*"));
daxsorbito
2009-10-24 07:29:49
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
2009-10-24 07:31:32
yah, I know but it seems the question didn't ask for any perfomance hit.
daxsorbito
2009-10-24 07:33:55
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
2009-10-24 08:45:10
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
2009-10-25 01:48:13
A:
var message = "hello world" ;
var newMessage = new String('*', message.Length);
Qwerty
2009-10-24 07:29:53