2

I have strings like this:

    00123_MassFlow
    0022245_VOlumeFlow
    122_447_Temperature

I have to split these strings with _ using 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?

2 Answers 2

8
"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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.