split string after comma and till string ends- asp.net c#
I have a string of type
开发者_如何学Cishan,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 ","
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);
var arr = string.Split(",");
var result = arr[arr.length-1];
sourcestring.Substring(sourcestring.IndexOf(','))
. You might want to check sourcestring.IndexOf(',')
for -1
for strings without ,
.
I know this question has already been answered, but you can use linq:
string str = "1,2,3,4,5";
str.Split(',').LastOrDefault();
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"
Use String.Split(",")
assign the result in to a string array and use what you want.
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
精彩评论