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开发者_StackOverflow中文版 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?
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.
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:
recipe = recipe.Substring(1);
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:
var rElements = recipe.Split(' ');
If you need to convert all of the string entries in the rElements array into integers you can do this:
var numArray = rElements.Select(e => int.Parse(e)).ToArray();
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:
var recipe = "搾68 00 00 37 00 45 00 00";
recipe = recipe.Substring(1);
var rElements = recipe.Split(' ');
var numArray = rElements.Select(e => int.Parse(e)).ToArray();
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?
using System.Text.RegularExpressions;
...
recipe = Regex.Replace(recipe, @"[^0-9\s]", string.Empty);
string[] rElements = recipe.Split(' ');
int num = int.Parse(rElements[0]);
精彩评论