Click here to Skip to main content
15,885,715 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am in the process of moving over from VB.NET to C# and I was wondering if anyone could help me with a problem I have been having.
Basically I am downloading some XML coordinates from an RSS feed but I don't know how I would seperate the 2 different numbers and put them into seperated text boxes called, lat.Text and lon.Text. I would know how to do it if they were the same length but as they are not it's causing me a headache.

Here is a sampele of the data.
51.103 1.800
50.400 0.000
50.3 0.2
50.3 -0.3
Posted

1 solution

Use String.Split().

As an example, if you called this on "51.103 1.800" :

C#
string data = "51.103 1.800";
string[] lines = data.Split();


Now lines would have 2 items, lines[0] would be "51.103" and lines[1] would be "1.800".

*Update*
----------
[Thanks to John]

Note how I don't pass any parameter to Split. What happens is that it will split based on any white space character (tab, space, multiple spaces, newline etc.)

If you specifically want to split on a single space, do it as follows:

C#
data.Split(' ');


*Another Update *
--------------------
[Thanks to GenJerDan]

If you want to be sure that the returned array won't have any empty strings, you can use an overload that takes a StringSplitOptions argument.

Example:

C#
string[] lines = data.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);


You cannot take advantage of the params feature in this overload so you need to use actual array creation syntax for the first parameter.
 
Share this answer
 
v10
Comments
Espen Harlinn 27-Jan-11 15:54pm    
5+ Nice and simple - provides just the right amount of information :)
Nish Nishant 27-Jan-11 15:55pm    
Thank you.
#realJSOP 27-Jan-11 16:00pm    
You forgot the " " in the call to Split. I fixed it for ya. Proposed as answer, btw.
Nish Nishant 27-Jan-11 16:14pm    
John, that's not needed. From the docs: "If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters."

Also if you hardcode a single literal space, it won't correctly handle multiple spaces, tabs or newlines. I'll undo the edit, and I hope that's alright with you.
#realJSOP 27-Jan-11 17:42pm    
That's ambiguous and less maintainable code. Just because you can do something doesn't mean you should. It's your answer, change it back if you want to.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900