C# ASCII转换器无法正常工作,输入字符串格式异常求助
解决ASCII值拼接转换的格式错误问题
嘿,别担心,新手遇到这种问题太正常啦!我来帮你拆解下问题出在哪,以及怎么修复~
首先看你代码里的错误根源:
- 你初始化
egg为空格,导致拼接后的字符串开头有个空格,比如处理名字"Alice"时,egg会变成" 6510810599101",之后你把temp.ToString()(初始是"0")和这个带空格的字符串拼在一起,得到"0 6510810599101"——这个字符串里有空格,转数字时当然会报「输入字符串格式不正确」的错误! - 另外
temp没有在每次处理新名字时重置,会累积上一次循环的值,导致后续的转换完全混乱。
修正后的代码方案
这里给你两种方案,根据你的需求选:
方案1:继续用double存储(注意精度限制)
如果一定要用double,我们可以去掉多余的空格,每次处理新名字时重置拼接容器,同时用更健壮的转换方式:
private static void AsciiConverter(string[] names, double[] AsciiNames) { // 遍历每个名字 for (int i = 0; i < names.Length; i++) { string currentName = names[i]; // 用StringBuilder拼接更高效,初始为空(不要加空格) StringBuilder asciiBuilder = new StringBuilder(); foreach (char c in currentName) { // 直接把字符的ASCII值转成字符串拼接 asciiBuilder.Append((int)c); } // 用TryParse避免转换失败时直接崩溃 if (double.TryParse(asciiBuilder.ToString(), out double convertedValue)) { AsciiNames[i] = convertedValue; } else { // 转换失败时可以设个默认值或者打印提示 AsciiNames[i] = double.NaN; Console.WriteLine($"警告:名称「{currentName}」转换失败,已设为NaN"); } } }
方案2:用BigInteger精确存储(推荐长名字场景)
如果你的名字比较长,拼接后的数字会非常大,double的精度有限(只能精确表示到2^53以内的整数),超过后会丢失精度。这种情况下推荐用BigInteger(需要引用System.Numerics命名空间):
using System.Numerics; private static void AsciiConverter(string[] names, BigInteger[] AsciiNames) { for (int i = 0; i < names.Length; i++) { string currentName = names[i]; StringBuilder asciiBuilder = new StringBuilder(); foreach (char c in currentName) { asciiBuilder.Append((int)c); } if (BigInteger.TryParse(asciiBuilder.ToString(), out BigInteger convertedValue)) { AsciiNames[i] = convertedValue; } else { AsciiNames[i] = BigInteger.Zero; Console.WriteLine($"警告:名称「{currentName}」转换失败,已设为0"); } } }
关键修复点总结
- 去掉了初始的空格,确保拼接的字符串是纯数字格式
- 每次处理新名字时重新初始化拼接容器,避免累积上一次的数据
- 用
TryParse代替直接Convert,让代码更健壮,能处理转换失败的情况
内容的提问来源于stack exchange,提问作者ChrisD
相关产品推荐
相关产品推荐

