使用C#从字符串中提取最后一个单词 [英] Extract the last word from a string using C#

查看:689
本文介绍了使用C#从字符串中提取最后一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串是这样的:

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

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

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

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

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

推荐答案

拆分是通过在 String 对象,可以使用数组索引或使用数组索引来检索最后一个元素最后 LINQ运算符。

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 lastWord = input.Split(' ').Last();

如果您没有LINQ,我将分两次进行:

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

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:


  • 将始终包含至少一个空格

  • 不以一个或多个空格结尾(如果这样,您可以对其进行裁剪)

然后,您可以使用此代码在堆上分配较少的对象,以供GC稍后使用:

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

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.

这篇关于使用C#从字符串中提取最后一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆