user14210426
user14210426

Reputation:

How can I remove everything of a string until the last comma in C#?

So I need to remove everything of a string until the last comma... (I'm reading the string from a file where I don't know how many commas there are.) I tried using .Trim / .TrimEnd but both don't do what I'm wanting it to do.

Here is an example what it kinda looks like: string example = object,1,4, 6,9-6, whg,19;

The string I'm trying to get: object

So the trim should ignore everthing until the last comma.

What I tried:

string exampleTrimmed = example.TrimEnd(',');

The output of that ► object,1,4, 6,9-6, whg19

string exampleTrimmed = example.Trim(',');

The output of that (not sure) ► object14 69-6 whg19

Upvotes: 0

Views: 748

Answers (3)

Mo B.
Mo B.

Reputation: 5805

What do you mean by "last" comma? And by "until"? Your example doesn't match your wording. Do you mean "the longest prefix not containing a comma"?

Then you could use s[..s.IndexOf(',')];

or to be safer, s[..((s.IndexOf(',') is int i && i < 0) ? s.Length : i)];

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 142008

You desired output ("object") does not match your description - to get it you need to strip everything after first occurrence of , (including it). For example, if you guaranteed to have , in your string, you can use String.Substring and String.IndexOf:

var s = "object,1,4, 6,9-6, whg,19";
Console.WriteLine(s.Substring(0, s.IndexOf(','))); // prints "object"

If you want to get everything after last comma you can use String.LastIndexOf:

Console.WriteLine(s.Substring(s.LastIndexOf(',') + 1)); // prints "19"

Upvotes: 2

Mikael
Mikael

Reputation: 982

If all you want is 'object' why not split by ',' and then call the array at index 0 like so:

    string example = "object,1,4, 6,9-6, whg,19";
    string[] parsed = example.Split(',');
    Console.WriteLine(parsed[0]);

Output: object

Edit: You say 'desired string: object' but you also say you want to ignore everything until the last comma.

Doing the above but using this: Console.WriteLine(parsed[parsed.Length-1]); outputs 19

Upvotes: 0

Related Questions