11

I have a string of type

ishan,training

I want to split the string after "," i.e i want the output as

training

NOTE: "," does not have a fixed index as the string value before "," is different at different times.

e.g ishant,marcela OR ishu,ponda OR amnarayan,mapusa etc...

From all the above strings i just need the part after ","

1
  • I'm not sure if what you want is to get the second word. I mean, if you've "a,b,c,d", you want to get "b,d"? Commented Apr 13, 2011 at 10:56

7 Answers 7

22

You can use String.Split:

string[] tokens = str.Split(',');
string last = tokens[tokens.Length - 1]

Or, a little simpler:

string last = str.Substring(str.LastIndexOf(',') + 1);
Sign up to request clarification or add additional context in comments.

2 Comments

Or you may want to use Linq: str.Split(',').LastOrDefault()
@Kobi Thank for this very simple but best approach so far! I have made a good use of str.Substring(str.LastIndexOf(',') + 1); in my project which working just fine! thanks again!
2
var arr = string.Split(",");
var result = arr[arr.length-1];

1 Comment

This will only give the last item. Is that what they want? From the title it seams they what everything after the comma. What if the string is 1,2,3,4,5?
2

sourcestring.Substring(sourcestring.IndexOf(',')). You might want to check sourcestring.IndexOf(',') for -1 for strings without ,.

Comments

2

I know this question has already been answered, but you can use linq:

string str = "1,2,3,4,5";
str.Split(',').LastOrDefault();

Comments

1

Although there are several comments mentioning the issue of multiple commas being found, there doesn't seem to be any mention of the solution for that:

string input = "1,2,3,4,5";
if (input.IndexOf(',') > 0)
{
    string afterFirstComma = input.Split(new char[] { ',' }, 2)[1];
}

This will make afterFirstComma equal to "2,3,4,5"

Comments

0

Use String.Split(",") assign the result in to a string array and use what you want.

Comments

0

Heres a VB version. I'm sure its easy to translate to C# though

 Dim str as string = "ishan,training"
 str = str.split(",")(1)

 return str

2 Comments

That works for the example above but, doesn't consider a string with multiple commas
Ah sorry, this might be better:.Split(",").Reverse(0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.