Reputation:
I'd like to replace every not digit character in string with a space character.
For ex.: "123X456Y78W9" -> "123 456 78 9"
Only resolution that I worked out is here:
string input = "123X456Y78W9";
string output = "";
foreach (char c in input)
if (c in (1, 2, 3, 4, 5, 6, 7, 8, 9, 0))
output += c;
else
output += ' ';
Is there are any simpler resolution?
Upvotes: 2
Views: 399
Reputation: 186833
Linq is an alternative to regular expressions:
string input = "123X456Y78W9";
string output = string.Concat(input.Select(c => c >= '0' && c <= '9' ? c : ' '));
Or if you want to preserve all unicode digits (say, persian ones - ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹
)
string output = string.Concat(input.Select(c => char.IsDigit(c) ? c : ' '));
Upvotes: 4
Reputation: 37487
You can use Regex.Replace()
with a character class of all non digits.
string output = Regex.Replace(input, @"\D", @" ");
Upvotes: 7