Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Break string into multiple parts

Tags:

c#

I have the following string:

+53.581N -113.587W 4.0 Km W of Edmonton, AB

In C# is there anyway to break this string out into Long. Latt. and then city state and discare the middle part?

So basically I want 3 strings:

Long
Latt
Location.

Is this possible with multiple forms of this string? They are in the same formate but obviously the data would be different.

Thanks

like image 936
user380432 Avatar asked Apr 21 '11 16:04

user380432


2 Answers

Use a regular expression to accomplish this - something like:

string input = @"+53.581N -113.587W 4.0 Km W of Edmonton, AB";
Match match = Regex.Match(input, @"^(?<latitude>[+\-]\d+\.\d+[NS])\s+(?<longitude>[+\-]\d+\.\d+[EW])\s+\d+\.\d+\s+Km\s+[NSEW]\s+of\s+(?<city>.*?),\s*(?<state>.*)$");
if (match.Success) {
    string lattitude = match.Groups["lattitude"].value;
    string longitude = match.Groups["longitude"].value;
    string city = match.Groups["city"].value;
    string state = match.Groups["state"].Value;
}
like image 161
Ken Richards Avatar answered Sep 24 '22 19:09

Ken Richards


Just like in all languages, it's possible with the power of the oh-so-awesome Regular Expressions.

If you are unfamiliar with Regular Expressions, I suggest you learn them. They're awesome. Seriously.

Here's a tutorial to get started with .NET regexps:

http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

like image 36
user703016 Avatar answered Sep 22 '22 19:09

user703016