当前位置:   article > 正文

C# 字符串罗马数字123转汉字一二三

C# 字符串罗马数字123转汉字一二三

要将字符串 "123" 转换为 "一二三",可以通过以下几种方法来实现。

1. 使用映射字典

可以创建一个映射字典,将数字字符映射到对应的中文数字,然后遍历原始字符串进行替换:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. public class Program
  5. {
  6. public static void Main()
  7. {
  8. string input = "123";
  9. string output = ConvertNumbersToChinese(input);
  10. Console.WriteLine(output); // 输出:一二三
  11. }
  12. public static string ConvertNumbersToChinese(string input)
  13. {
  14. // 创建数字到中文的映射字典
  15. Dictionary<char, string> numberToChinese = new Dictionary<char, string>
  16. {
  17. {'0', "零"},
  18. {'1', "一"},
  19. {'2', "二"},
  20. {'3', "三"},
  21. {'4', "四"},
  22. {'5', "五"},
  23. {'6', "六"},
  24. {'7', "七"},
  25. {'8', "八"},
  26. {'9', "九"}
  27. };
  28. StringBuilder sb = new StringBuilder();
  29. foreach (char c in input)
  30. {
  31. if (numberToChinese.ContainsKey(c))
  32. {
  33. sb.Append(numberToChinese[c]);
  34. }
  35. else
  36. {
  37. // 处理非数字字符(可选)
  38. sb.Append(c);
  39. }
  40. }
  41. return sb.ToString();
  42. }
  43. }

2. 使用 Regex 和 Replace 方法

如果你有更多的数字字符串需要转换,可以使用正则表达式和 Replace 方法,但这种方法通常不如映射字典直观和高效。

  1. using System;
  2. using System.Text.RegularExpressions;
  3. public class Program
  4. {
  5. public static void Main()
  6. {
  7. string input = "123";
  8. string output = ConvertNumbersToChinese(input);
  9. Console.WriteLine(output); // 输出:一二三
  10. }
  11. public static string ConvertNumbersToChinese(string input)
  12. {
  13. return Regex.Replace(input, "[0-9]", m =>
  14. {
  15. switch (m.Value)
  16. {
  17. case "0": return "零";
  18. case "1": return "一";
  19. case "2": return "二";
  20. case "3": return "三";
  21. case "4": return "四";
  22. case "5": return "五";
  23. case "6": return "六";
  24. case "7": return "七";
  25. case "8": return "八";
  26. case "9": return "九";
  27. default: return m.Value;
  28. }
  29. });
  30. }
  31. }

3. 使用国际化库

如果需要处理更复杂的情况或支持多语言,考虑使用国际化库(如 Humanizer),但这通常涉及额外的库引入和配置。

选择合适的方法

  • 映射字典: 适用于简单的数字转换,代码清晰,效率高。
  • 正则表达式: 灵活处理多个模式,但在性能上可能稍逊一筹。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/882534
推荐阅读
相关标签
  

闽ICP备14008679号