c#FormatException未处理
我正在解析游戏中的聊天,我得到这个字符串“榨68 00 00 37 00 45 00 00”
recipe = recipe.Replace("搾", "");
string[] rElements = new string[8];
rElements = recipe.Split(' ');
int num = int.Parse(rElements[0]);
我在最后一行得到一个我不明白的格式异常。它说输入字符串的格式不正确。我检查了调试器,第一个元素显示它是“68”。有人知道发生了什么事吗?
I'm parsing chat from a game and i get this string "搾68 00 00 37 00 45 00 00"
recipe = recipe.Replace("搾", "");
string[] rElements = new string[8];
rElements = recipe.Split(' ');
int num = int.Parse(rElements[0]);
I get a Format exception on that last line that i don't understand. It says that input string is not in the right format. I have checked the debugger and the first element says it is "68". Anyone have any clue what is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
给定提供的字符串
榨68 00 00 37 00 45 00 00
,您的代码将按预期执行。num
是 68。我建议您的输入字符串和数组的第一个元素不是您想象的那样。在尝试解析之前尝试将它们打印出来。Your code executes as expected, given the provided string
搾68 00 00 37 00 45 00 00
.num
is 68. I propose that your input string, and the first element of the array, are not what you think they are. Try to print them out before attempting the parse.如前所述,给定提供的字符串,您的代码会将 num 设置为 68。以下是一些提示:
如果您只想删除第一个字符并且不需要匹配它,您可以使用:
Split 方法将创建一个包含 8 个元素的新数组,因此没有理由用数组初始化 rElements。相反,您可以使用:
如果您需要将 rElements 数组中的所有字符串条目转换为整数,您可以这样做:
当然,如果您需要检查每一项,您可以使用带有 TryParse 或 try/catch 的循环。把它们放在一起,你会得到:
As noted already, given the string provided, your code will set num to 68. Here are a few pointers:
If you just want to remove the first character and don't need to match it, you can use:
The Split method will create a new array with 8 elements, so there is no reason to initialize rElements with an array. Instead you can use:
If you need to convert all of the string entries in the rElements array into integers you can do this:
Of course, if you need to check each one, you can use a loop with either TryParse or a try/catch. Putting it all together, you get:
我假设您只是复制/粘贴了输入字符串/代码,所以我认为您正在处理的问题是输入字符串的编码。在我的屏幕上,我看到你的第一个字符是汉字“zhà”,意思是“压迫”或“榨取”。因此,尽管您的示例输入字符串和代码有效,但后续输入字符串可能包含与示例输入字符串中的字符不同的 Unicode 字符?
尝试使用 REGEX 删除不需要的号码?
I'm assuming you simply copied/pasted your input string / code so I think the issue you're dealing with is the encoding of your input string. On my screen, I see your first character as the Chinese character zhà, which means oppress or to extract. So although your sample input string and code works, perhaps subsequent input strings contain different Unicode characters, other than the one in your sample input string?
Try using REGEX to remove unwanted numbers?