You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字符串中的数字替换为对应英文单词?现有代码报错求解

问题分析与修复

直接触发异常的原因

你的代码存在一个致命的参数错误:调用Remove方法时,第一个参数传成了sample[index1](获取对应索引的字符),而非索引值index1。sample[index1]是char类型,会被隐式转换为对应的ASCII整数(比如字符'1'会转为49),这个数值远超过字符串实际长度,因此触发了ArgumentOutOfRangeException。

另外,字符串定义末尾的逗号属于语法错误,需要改成分号。

修复后的基础代码

先修正上述错误,保证代码能正常运行:

string[] numwords = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
string sample = "Hello MY naMe is Joe Bloggs 1234567 10 :-)"; // 修正逗号为分号,添加10测试
for(int x=0; x<nums.Length; x++)
{
    string numStr = Convert.ToString(nums[x]);
    if (sample.Contains(numStr))
    {
        int index1 = sample.IndexOf(numStr);
        // 修复Remove参数,同时根据数字长度删除对应字符数
        sample = sample.Remove(index1, numStr.Length);
        sample = sample.Insert(index1, numwords[x]);
    }
}
Console.WriteLine(sample);

进一步优化逻辑

上面的代码仅解决了异常问题,仍存在逻辑缺陷:只会替换每个数字的第一个出现位置,且会先处理单个数字(比如1),导致多位数(比如10)被拆成"one0"无法正确替换。以下是两种优化方案:

方案1:批量替换+按数字长度降序处理

先处理多位数,再处理单个数字,避免拆分;用Replace一次性替换所有匹配项,效率更高:

string[] numwords = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" };
int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
string sample = "Hello MY naMe is Joe Bloggs 1234567 10 1 10 :-)";

// 配对数字与单词,按数字字符串长度降序排序
var numPairs = nums.Zip(numwords, (n, w) => new { NumStr = n.ToString(), Word = w })
                   .OrderByDescending(p => p.NumStr.Length);

foreach (var pair in numPairs)
{
    sample = sample.Replace(pair.NumStr, pair.Word);
}

Console.WriteLine(sample);

方案2:正则表达式匹配任意数字

如果需要支持大于10的数字或更灵活的匹配,正则表达式是更优选择:

// 定义数字-单词映射字典
var numWordMap = new Dictionary<string, string>
{
    {"0", "zero"}, {"1", "one"}, {"2", "two"}, {"3", "three"}, {"4", "four"},
    {"5", "five"}, {"6", "six"}, {"7", "seven"}, {"8", "eight"}, {"9", "nine"},
    {"10", "ten"}
};

string sample = "Hello MY naMe is Joe Bloggs 1234567 10 1 10 :-)";

// 匹配所有数字,替换为对应单词;无对应单词则保留原数字
string result = System.Text.RegularExpressions.Regex.Replace(sample, @"\d+", match => 
{
    numWordMap.TryGetValue(match.Value, out var word);
    return word ?? match.Value;
});

Console.WriteLine(result);

内容的提问来源于stack exchange,提问作者charliewhittaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:05:24