赞
踩
要将字符串 "123"
转换为 "一二三"
,可以通过以下几种方法来实现。
可以创建一个映射字典,将数字字符映射到对应的中文数字,然后遍历原始字符串进行替换:
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- public class Program
- {
- public static void Main()
- {
- string input = "123";
- string output = ConvertNumbersToChinese(input);
- Console.WriteLine(output); // 输出:一二三
- }
-
- public static string ConvertNumbersToChinese(string input)
- {
- // 创建数字到中文的映射字典
- Dictionary<char, string> numberToChinese = new Dictionary<char, string>
- {
- {'0', "零"},
- {'1', "一"},
- {'2', "二"},
- {'3', "三"},
- {'4', "四"},
- {'5', "五"},
- {'6', "六"},
- {'7', "七"},
- {'8', "八"},
- {'9', "九"}
- };
-
- StringBuilder sb = new StringBuilder();
-
- foreach (char c in input)
- {
- if (numberToChinese.ContainsKey(c))
- {
- sb.Append(numberToChinese[c]);
- }
- else
- {
- // 处理非数字字符(可选)
- sb.Append(c);
- }
- }
-
- return sb.ToString();
- }
- }

Regex
和 Replace
方法如果你有更多的数字字符串需要转换,可以使用正则表达式和 Replace
方法,但这种方法通常不如映射字典直观和高效。
- using System;
- using System.Text.RegularExpressions;
-
- public class Program
- {
- public static void Main()
- {
- string input = "123";
- string output = ConvertNumbersToChinese(input);
- Console.WriteLine(output); // 输出:一二三
- }
-
- public static string ConvertNumbersToChinese(string input)
- {
- return Regex.Replace(input, "[0-9]", m =>
- {
- switch (m.Value)
- {
- case "0": return "零";
- case "1": return "一";
- case "2": return "二";
- case "3": return "三";
- case "4": return "四";
- case "5": return "五";
- case "6": return "六";
- case "7": return "七";
- case "8": return "八";
- case "9": return "九";
- default: return m.Value;
- }
- });
- }
- }

如果需要处理更复杂的情况或支持多语言,考虑使用国际化库(如 Humanizer
),但这通常涉及额外的库引入和配置。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。