Reputation: 594
I have a string North Ridge NJ 01234
I want to split them into City, State and zip to store into Database. I was trying to split based on spaces, I get four substrings instead of three. Is there any way I can split backwards but only on two spaces?
Upvotes: 0
Views: 135
Reputation: 150238
If you can assume the last array element is the ZIP and the one before that the state code
string[] words = s.Split(' ');
var zip = words[words.Length - 1];
var state = words[words.Length - 2];
var city = string.Join(" ", words, 0, words.Length - 2);
Makes use of a string.Join overload that lets you specify the start index and number of array elements to join.
Note that the code can fail if the assumptions fail to hold. For example, if it is possible for data to be delimited by either space or tab, you will want to provide both characters to string.Split(). If it is possible that bad data entry could lead to multiple space characters, you'll want to check for that possibility before running this code (e.g. New York, NY 12345
).
Upvotes: 6
Reputation: 651
I used a simple regular expression.
> string test = "North Ridge NJ 01234";
> Regex address = new Regex(@"([\w ]*) (\w\w) (\d\d\d\d\d)");
> address.Split(test)
string[5] { "", "North Ridge", "NJ", "01234", "" }
If anyone knows a way to not get the empty strings back, I'd love to hear it. This should work for any address you have of this form, though.
Upvotes: 0
Reputation: 1890
Maybe something like this:
static void Main()
{
string s = "North Ridge NJ 01234";
//Following gives {01234, NJ, Ridge, North}
var words = s.Split(' ').ToList();
words.Reverse();
string zip = words[0];
string state = words[1];
string city = s.Replace(state + " " + zip, "");
}
Upvotes: -2