简体   繁体   English

取.Split('')的所有元素并取最后一个或排除最后一个项目

[英]Take all elements of .Split (' ') and take last OR exclude last item

I have an inconsistend address field which I am reading from excel. 我有一个从Excel中读取的不一致地址字段。 I need to split this field and enter those 2 values into two list properties. 我需要拆分此字段,然后将这2个值输入到两个列表属性中。

the content could be something like this 内容可能是这样的

At the gates 42 在大门口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" 我需要将其余部分分开,然后在属性“街道”上添加“在大门口”,在属性“ number”上添加“ 42”

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? 我该如何用Linq分割此字符串,并只排除最后一个数字才能上街?

Kind regards 亲切的问候

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. 如果需要更大的灵活性,也可以考虑使用正则表达式。

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
    }

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

I would use LastIndexOf for this (if you can safely assume that your house numbers don't have spaces in): 我会为此使用LastIndexOf(如果可以安全地假定您的门牌号中没有空格):

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... 请注意,虽然让Excel为您完成工作可能会更容易,但您可以在工作表中使用公式来执行相同的功能,因此...

This gives you the street name (assuming your original value is in cell A1, just replace all occurrences of A1 otherwise): 这为您提供街道名称(假设您的原始值位于单元格A1中,否则请替换所有出现的A1):

=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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM