Converting string array to int

你离开我真会死。 提交于 2020-01-05 05:47:07

问题


I'm having a weird problem, trying to take a string from a string array and convert it to an integer. Take a look at this code snippet:

string date = "‎21/‎07/‎2010 ‏‎13:50";
var date1 = date.Split(' ')[0];
string[] dateArray = date1.Split('/');

string s = "21";
string t1 = dateArray[0];

bool e = string.Compare(s, t1) == 0;        //TRUE

int good = Convert.ToInt32(s);            //WORKING!
int bad = Convert.ToInt32(t1);  //Format exception - Input string was not in a correct format.

Can someone please explain why the conversion with s works, while with t1 fails?


回答1:


Your string is full of hidden characters, causing it to break. There's four U+200E and one U+200F

Here's a clean string to try on:

string date = "21/07/2010 13:50";



回答2:


Why do you use string.Compare(s, t1) == 0 to test if the strings are equal? This overload of Compare does a culture sensitive comparison. But it doesn't mean that the strings are identical. To check if the strings consist of identical "sequences" of char values, use ordinal comparison. Ordinal comparison can be done, for example, with

bool e = s == t1;

In your case, the strings have different Lengths, and they also differ on the first index, s[0] != t1[0].

Your string date contains right-to-left marks and left-to-right marks. This may happen because you copy-paste from an Arabic text (or another language written in the "wrong" direction).

To remove these characters in the ends of your string (not in the middle), you can use something like

t1 = t1.Trim('\u200E', '\u200F');


来源:https://stackoverflow.com/questions/13770105/converting-string-array-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!