simple string parsing questions

Feels like homework, but I was in a good mood.

22:28 [ Flav_] then you can do something like: int foo; if
(int.TryParse(textbox.Text, out foo)) { … do something with
the int foo … }
22:29 [ Flav_] int.TryParse looks at the string you pass in, and if it can
parse it as an int, sets the out parameter to the parsed value
and returns true. If it can’t, it returns false
22:30 [ Maxtors] YES! thanks man iv been looking for that for ages… 😛
22:30 [ Maxtors] lol
22:30 [ Flav_] it wasn’t in VS 2003 and earlier – a nice addition to .NET 2.0
22:31 [ Maxtors] hehe:P
22:31 [ Flav_] IIRC double had it back then, but not int
22:31 [ Maxtors] but what if the input == a double value
22:32 [ Flav_] it depends on what you want to do – since “17” can parse as both
an int and a double, you could try one then the other
22:32 [ Flav_] the easier route may be to just parse it as a double regardless
22:33 [ Flav_] then you can do something like: double foo; if
(double.TryParse(textbox.Text, out foo)) { … do something with
the double foo … }
22:33 [ Maxtors] ok… makes sence
22:33 [ Flav_] i guess it depends on how you want to treat them differently
22:33 [ Maxtors] but why foo… i’ve heard it before… is it just a common
thing or a real syntax
22:33 [ Flav_] just common variable name in examples
22:34 [ Flav_] it can be called anything
22:34 [ Maxtors] ok
22:34 [ Flav_] double parsedDouble; if (double.TryParse(textbox.Text, out
parsedDouble)) { … do something with the double parsedDouble
… }
22:35 [ Maxtors] so what is does is that it TRYs to parse it as a double and if
it is sucsessful the do the thing between the {…}
22:35 [ Flav_] yes
22:36 [ Maxtors] ok…
22:40 [ Maxtors] in VB 6.0 you could just write len(text1.text)… to count
the characters can you do that in C#
22:40 [ Flav_] text1.Text.Length
22:40 [ Maxtors] also how can i delete the 1st character in a string then make
it a double…
22:40 [ Flav_] every string has a .Length property that will give you the
number of characters in the string
22:40 [ Maxtors] wait ill give you an example
22:40 [ Flav_] delete the first character is: someString =
someString.Substring(1);
22:41 [ Flav_] if you know it’s a double for sure already, you could then
double someDouble = double.Parse(someString);
22:41 [ Flav_] otherwise, do the same double parsedDouble; if
(double.TryParse(someString, out parsedDouble)) { … }
22:42 [ Maxtors] my label text is “$100″… then i whant to add $10 to that…
22:42 [ Flav_] textbox.Text = “$” + int.Parse(textbox.Text.Substring(1));
22:43 [ Flav_] whoops
22:43 [ Flav_] textbox.Text = “$” + (int.Parse(textbox.Text.Substring(1)) + 10);
22:43 [ Flav_] forgot to add the 10

Advertisements