C # Break a string into several parts

I have the following line:

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

In C #, there is anyway to split this string into Long. Latt. and then the city state and withdraw the middle part?

So basically I want 3 lines:

Long
Latt
Location.

Is this possible with multiple forms of this line? They are in the same form, but, obviously, the data will be different.

thank

+5
source share
4 answers

Use a regex 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;
}
+4
source

Just like in all languages, this is possible thanks to the power of oh-so-amazing regular expressions.

If you are not familiar with regular expressions, I suggest you study them. They are awesome. Seriously.

Here is a .NET regexps tutorial:

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

+2

. . http://www.c-sharpcorner.com/uploadfile/prasad_1/regexppsd12062005021717am/regexppsd.aspx.

The sample that should work is as follows (given the one example you provided):

^([+-]\d+\.\d+\w) ([+-]\d+\.\d+\w) (.*?)$
+1
source

Use the string.Split command (Char [], Int32)

var input = "+53.581N -113.587W 4.0 Km W of Edmonton, AB";
var splitArray = input.Split(new char[]{' '},3);

You will get Long, Lat and Location. (pay attention to 3 - this is a partition of the array three times)

Response to other answers suggesting Regex:

Please avoid regular expressions if the format is the same. The above option is much simpler, and the regular expression, as a rule, becomes incomprehensible very quickly.

+1
source

All Articles