开发者

C# Break string into multiple parts

开发者 https://www.devze.com 2023-02-27 10:39 出处:网络
I have th开发者_开发问答e 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 pa

I have th开发者_开发问答e 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


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;
}


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


You can use regex to capture those parts. See http://www.c-sharpcorner.com/uploadfile/prasad_1/regexppsd12062005021717am/regexppsd.aspx.

A pattern that should work is the following (considering the one example you provided):

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


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

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

You will get the Long, Lat and Location. ( note the 3 - this splits the array three times )

Response to other answers suggesting Regex:

Please avoid regex if the format is going to be the same. The above option is much more simpler and the regex tend to get incomprehensible very quickly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号