开发者

To get specific part of a string in c# [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts开发者_JAVA技巧, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜