string split in c#

后端 未结 2 1729
遥遥无期
遥遥无期 2020-12-12 01:17

I have strings like this:

    00123_MassFlow
    0022245_VOlumeFlow
    122_447_Temperature

I have to split these strings with _

相关标签:
2条回答
  • 2020-12-12 02:00

    If your input is in a single string, you can use string.Split('\n') to get it into a collection:

    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. From there, you can use LINQ to accomplish this easily:

    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.

    0 讨论(0)
  • 2020-12-12 02:04
    "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.

    0 讨论(0)
提交回复
热议问题