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?
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";
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 Length
s, 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');