[英]How can i replace many special character including white space with single character?
[英]How can I replace no digit character with space character?
我想用空格字符替換字符串中的每個非數字 字符 。
例如: "123X456Y78W9" -> "123 456 78 9"
我得出的唯一解決方案是:
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 += ' ';
有沒有更簡單的解決方案?
您可以將Regex.Replace()
與所有非數字字符類一起使用。
string output = Regex.Replace(input, @"\D", @" ");
Linq是正則表達式的替代方法:
string input = "123X456Y78W9";
string output = string.Concat(input.Select(c => c >= '0' && c <= '9' ? c : ' '));
或者,如果您想保留所有unicode數字 (例如, 波斯 數字 ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹
)
string output = string.Concat(input.Select(c => char.IsDigit(c) ? c : ' '));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.