开发者

Looking for the simplest way to extract tow strings from another in C#

I have the following strings:

string a = "1. testdata";
string b = "12. testdata xxx";

What I would like is to be 开发者_如何学Pythonable to extract the number into one string and the characters following the number into another. I tried using .IndexOf(".") and then remove, trim and substrings. If possible I would like to find something simpler as I have this to do in a lot of parts of my code.


if the format is always the same you could do:

a.Split('.');


Proposed solutions so far are not correct. First, after Split('.') or Split(".") you will have space in the beginning of second substring. Second, if you have more than one dot - you'll have to do something yet after the split.

More robust solution is below:

string a = "11. Test string. With dots.";
var res = a.Split(new[] {". "}, 2, StringSplitOptions.None);
string number = res[0];
string val = res[1];

Argument 2 specifies maximum number of strings to return. Thus when you have several dots - it will make a split only at the first.


string[]list = a.Split(".");
string numbers = list[0];
string chars = list[1];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜