Reputation: 23927
I have an inconsistend address field which I am reading from excel. I need to split this field and enter those 2 values into two list properties.
the content could be something like this
At the gates 42
I need to split the number from the rest and add "At the gates" to the property "Street" and "42" to the property "number"
I have solved the problem with taking the number with this:
Number = Convert.ToString(ws.Cells[j + 3, i + 2].Value).Split(' ').LastOrDefault()
How can I split this string with Linq and just exclude the last number to get the street?
Kind regards
Upvotes: 0
Views: 1418
Reputation: 3430
Use regex so you can also have it flexible to your needs.
Here's a sample:
static void Main(string[] args)
{
Regex regex = new Regex(@"(?<words>[A-Za-z ]+)(?<digits>[0-9]+)");
string input = "At the gates 42";
var match = regex.Match(input);
var a = match.Groups["words"].Value; //At the gates
var b = match.Groups["digits"].Value; //42
}
Upvotes: 2
Reputation: 1
I would use LastIndexOf for this (if you can safely assume that your house numbers don't have spaces in):
var original = Convert.ToString(ws.Cells[j + 3, i + 2].Value).Split().LastOrDefault()
var street = original.Substring(1, original.LastIndexOf(' '))
var number = original.Substring(original.LastIndexOf(' ') + 1)
Note that it might be easier to get Excel to do the work for you though, you could use a formula in your sheet to perform the same function, so...
This gives you the street name (assuming your original value is in cell A1, just replace all occurrences of A1 otherwise):
=MID(A1,1,LOOKUP(9.9999999999E+307,FIND(" ",A1,ROW($1:$1024)))-1)
and this gives you the number:
=MID(A1,LOOKUP(9.9999999999E+307,FIND(" ",A1,ROW($1:$1024)))+1,LEN(A1))
Upvotes: 0
Reputation: 11025
You could just do this:
String[] sa = Convert.ToString(ws.Cells[j + 3, i + 2].Value).Split(' ');
Int32 number = Convert.ToInt32(sa[sa.Length - 1]);
String street = String.Join(" ", sa.Take(sa.Length - 1));
Upvotes: 0
Reputation: 32587
Splitting the string is a bit too much here. You just need to find the last occurence of " " and split at this position:
var address = "At the gates 42";
var idx = address.LastIndexOf(' ');
var street = address.Substring(0, idx);
var number = address.Substring(idx + 1);
Also consider using regular expressions if you need more flexibility.
Upvotes: 2