由字母组成的数千字符串分隔符

时间:2017-03-22 19:18:51

标签: c# .net string

是否有任何简单的解决方案可以将千位分隔符添加到以字母为后缀的字符串中?

例如,我按原样获取数据:

123456 km

我想把它变成:

123,456 km

是否有一个简单的解决方案,无需剥离后缀的数据,执行String.Format("0:n0"),然后重新添加后缀?

编辑:后缀不是前缀。

3 个答案:

答案 0 :(得分:2)

您可以尝试正则表达式:只需提取并替换所有足够长的值,例如

  string source = "the distance was 123456.47 km and the speed was 1234 m/s";

  string result = Regex.Replace(
    source,
    @"([0-9]{4,})((\s*[a-zA-Z]+)|(\.))",
    match => double.Parse(match.Groups[1].Value).ToString("#,##0") +
             match.Groups[2].Value);

  Console.Write(result);

结果

  the distance was 123,456.47 km and the speed was 1,234 m/s

答案 1 :(得分:2)

将此用作匹配评估器:

 static string Seprator(Match m)
 {
     return int.Parse(m.ToString()).ToString("N0");
 }

然后这会给你你想要的结果:

string result = Regex.Replace(a, "[0-9]+",new MatchEvaluator(Seprator));

这是Live Demo

答案 2 :(得分:1)

试试这个:

string number = String.Format("0:n0", double.Parse(yournumber.Split(" ").GetValue(0).ToString())) + yournumber.Split(" ").GetValue(1).ToString();
相关问题