To get specific part of a string in c# [closed]
I have a string
string a = "abc,xyz,wer";
Now, I need a part of this string like
string b = "abc";
I need everything before the first comma.How shall I get it?
Something like this?
string b = a.Split(',')[0];
You can use Substring:
string b = a.Substring(0,3);
Your question is vague (are you always looking for the first part?), but you can get the exact output you asked for with string.Split
:
string[] substrings = a.Split(',');
b = substrings[0];
Console.WriteLine(b);
Output:
abc
If you want to get the strings separated by the ,
you can use
string b = a.Split(',')[0];
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
精彩评论