简体   繁体   English

字符串拆分为c#

[英]string split in c#

I have strings like this: 我有这样的字符串:

    00123_MassFlow
    0022245_VOlumeFlow
    122_447_Temperature

I have to split these strings with _ using C#. 我必须使用C#将这些字符串拆分为_ _ may appear multiple places but i have to take last value. _可能出现多个地方,但我必须采取最后一个值。

My should be like this: 我应该是这样的:

    MassFlow
    VOlumeFlow
    Temperature

How i can achieve this? 我怎么能做到这一点?

"122_447_Temperature".Split('_').Last();

If you don't mind the extra overhead of creating an array and throwing away a bunch of strings. 如果你不介意创建一个数组并抛弃一堆字符串的额外开销。 It won't be as fast as using LastIndexOf and Substring manually, but it's a ton easier to read and maintain, IMO. 它不会像手动使用LastIndexOfSubstring一样快,但它更容易阅读和维护,IMO。

If your input is in a single string, you can use string.Split('\\n') to get it into a collection: 如果您的输入是单个字符串,则可以使用string.Split('\\n')将其输入集合:

string input = @"00123_MassFlow
0022245_VOlumeFlow
122_447_Temperature";

var items = input.Split('\n');

Otherwise, I'm going to assume your strings are already in a collection called items . 否则,我将假设你的字符串已经在一个名为items的集合中。 From there, you can use LINQ to accomplish this easily: 从那里,您可以使用LINQ轻松完成此任务:

List<string> result = (from x in items
                       let y = x.Trim()
                       select y.Substring(y.LastIndexOf('_') + 1)).ToList();

result will contain the strings MassFlow , VOlumeFlow , and Temperature . result将包含字符串MassFlowVOlumeFlowTemperature

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

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