我有很多带数字的字符串。我需要重新格式化字符串以在所有数字序列之后添加逗号。数字有时可能包含其他字符,包括 12-3 或 12/4,例如
- “你好 1234 再见”应该是“你好 1234,再见”
- “987中间文字654”应该是“ 987中间文字654 ”
- “1/2是一个包含其他字符的数字”应该是“ 1/2,是一个包含其他字符的数字”
- “这也是 12-3 有数字”应该是“这也是 12-3,有数字”
谢谢你们
编辑: 我的示例不考虑任何特殊字符。我最初没有包括它,因为我认为如果有人能更有效地做到这一点,我会得到一个全新的视角——我的错!
private static string CommaAfterNumbers(string input)
{
string output = null;
string[] splitBySpace = Regex.Split(input, " ");
foreach (string value in splitBySpace)
{
if (!string.IsNullOrEmpty(value))
{
if (int.TryParse(value, out int parsed))
{
output += $"{parsed},";
}
else
{
output += $"{value} ";
}
}
}
return output;
}
