使用C#从字符串中提取最后一个单词

时间:2022-09-13 14:17:55

My string is like this:

我的字符串是这样的:

string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";

Here actually I want to extract the last word, 'API', and return.

实际上我想提取最后一个词'API'并返回。

What would be the C# code to do the above extraction?

进行上述提取的C#代码是什么?

7 个解决方案

#1


56  

Well, the naive implementation to that would be to simply split on each space and take the last element.

那么,天真的实现就是简单地拆分每个空间并采用最后一个元素。

Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator.

使用String对象上的实例方法完成拆分,可以使用数组索引或使用Last LINQ运算符检索最后一个元素。

End result:

最终结果:

string lastWord = input.Split(' ').Last();

If you don't have LINQ, I would do it in two operations:

如果你没有LINQ,我会在两个操作中完成:

string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];

While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.

虽然这适用于此字符串,但它可能不适用于稍微不同的字符串,因此要么您必须弄清楚如何相应地更改代码,要么发布所有规则。

string input = ".... ,API";

Here, the comma would be part of the "word".

这里,逗号将是“单词”的一部分。

Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules:

此外,如果获取单词的第一种方法是正确的,即最后一个空格之后的所有内容,并且您的字符串符合以下规则:

  • Will always contain at least one space
  • 将始终包含至少一个空格
  • Does not end with one or more spaces (in case of this you can trim it)
  • 不以一个或多个空格结束(如果是这样,你可以修剪它)

Then you can use this code that will allocate fewer objects on the heap for GC to worry about later:

然后,您可以使用此代码在堆上分配更少的对象,以便GC稍后担心:

string lastWord = input.Substring(input.LastIndexOf(' ') + 1);

However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.

但是,如果你需要考虑逗号,分号和诸如此类的东西,那么使用分割的第一种方法是最好的;要跟踪的东西越来越少。

#2


12  

First:

第一:

using System.Linq; // System.Core.dll

then

然后

string last = input.Split(' ').LastOrDefault();

// or

string last = input.Trim().Split(' ').LastOrDefault();

// or

string last = input.Trim().Split(' ').LastOrDefault().Trim();

#3


7  

var last = input.Substring(input.LastIndexOf(' ')).TrimStart();

var last = input.Substring(input.LastIndexOf(''))。TrimStart();

This method doesn't allocate an entire array of strings as the others do.

此方法不像其他方法那样分配整个字符串数组。

#4


3  

string workingInput = input.Trim();
string last = workingInput.Substring(workingInput.LastIndexOf(' ')).Trim();

Although this may fail if you have no spaces in the string. I think splitting is unnecessarily intensive just for one word :)

虽然如果字符串中没有空格,这可能会失败。我认为分裂是不必要的密集只是一个字:)

#5


1  

var lastWord = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Last();

#6


1  

static class Extensions
{
    private static readonly char[] DefaultDelimeters = new char[]{' ', '.'};

    public string LastWord(this string StringValue)
    {
        return LastWord(StringValue, DefaultDelimeters);
    }

    public string LastWord(this string StringValue, char[] Delimeters)
    {
        int index = StringValue.LastIndexOfAny(Delimeters);

        if(index>-1)
            return StringValue.Substring(index);
        else
            return null;
    }
}

class Application
{
    public void DoWork()
    {
        string sentence = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
        string lastWord = sentence.LastWord();
    }
}

#7


0  

string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
var a = input.Split(' ');
Console.WriteLine(a[a.Length-1]);

#1


56  

Well, the naive implementation to that would be to simply split on each space and take the last element.

那么,天真的实现就是简单地拆分每个空间并采用最后一个元素。

Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator.

使用String对象上的实例方法完成拆分,可以使用数组索引或使用Last LINQ运算符检索最后一个元素。

End result:

最终结果:

string lastWord = input.Split(' ').Last();

If you don't have LINQ, I would do it in two operations:

如果你没有LINQ,我会在两个操作中完成:

string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];

While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.

虽然这适用于此字符串,但它可能不适用于稍微不同的字符串,因此要么您必须弄清楚如何相应地更改代码,要么发布所有规则。

string input = ".... ,API";

Here, the comma would be part of the "word".

这里,逗号将是“单词”的一部分。

Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules:

此外,如果获取单词的第一种方法是正确的,即最后一个空格之后的所有内容,并且您的字符串符合以下规则:

  • Will always contain at least one space
  • 将始终包含至少一个空格
  • Does not end with one or more spaces (in case of this you can trim it)
  • 不以一个或多个空格结束(如果是这样,你可以修剪它)

Then you can use this code that will allocate fewer objects on the heap for GC to worry about later:

然后,您可以使用此代码在堆上分配更少的对象,以便GC稍后担心:

string lastWord = input.Substring(input.LastIndexOf(' ') + 1);

However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.

但是,如果你需要考虑逗号,分号和诸如此类的东西,那么使用分割的第一种方法是最好的;要跟踪的东西越来越少。

#2


12  

First:

第一:

using System.Linq; // System.Core.dll

then

然后

string last = input.Split(' ').LastOrDefault();

// or

string last = input.Trim().Split(' ').LastOrDefault();

// or

string last = input.Trim().Split(' ').LastOrDefault().Trim();

#3


7  

var last = input.Substring(input.LastIndexOf(' ')).TrimStart();

var last = input.Substring(input.LastIndexOf(''))。TrimStart();

This method doesn't allocate an entire array of strings as the others do.

此方法不像其他方法那样分配整个字符串数组。

#4


3  

string workingInput = input.Trim();
string last = workingInput.Substring(workingInput.LastIndexOf(' ')).Trim();

Although this may fail if you have no spaces in the string. I think splitting is unnecessarily intensive just for one word :)

虽然如果字符串中没有空格,这可能会失败。我认为分裂是不必要的密集只是一个字:)

#5


1  

var lastWord = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Last();

#6


1  

static class Extensions
{
    private static readonly char[] DefaultDelimeters = new char[]{' ', '.'};

    public string LastWord(this string StringValue)
    {
        return LastWord(StringValue, DefaultDelimeters);
    }

    public string LastWord(this string StringValue, char[] Delimeters)
    {
        int index = StringValue.LastIndexOfAny(Delimeters);

        if(index>-1)
            return StringValue.Substring(index);
        else
            return null;
    }
}

class Application
{
    public void DoWork()
    {
        string sentence = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
        string lastWord = sentence.LastWord();
    }
}

#7


0  

string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
var a = input.Split(' ');
Console.WriteLine(a[a.Length-1]);