开发者

How can I parse an integer and the remaining string from my string?

I have strings that look like this:

1. abc
2. def
88. ghi

I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number 开发者_C百科and a string?


May not be the best way, but, split by the ". " (thank you Kirk)

everything afterwards is a string, and everything before will be a number.


You can call IndexOf and Substring:

int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();


        var input = "1. abc";
        var match = Regex.Match(input, @"(?<Number>\d+)\. (?<Text>.*)");
        var number = int.Parse(match.Groups["Number"].Value);
        var text = match.Groups["Text"].Value;


This should work:

public void Parse(string input)
{
    string[] parts = input.Split('.');
    int number = int.Parse(parts[0]); // convert the number to int
    string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}

The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.

Then you can convert the number into an integer with int.Parse.


public Tuple<int, string> SplitItem(string item)
{
    var parts = item.Split(new[] { '.' });
    return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}

var tokens = SplitItem("1. abc");
int number = tokens.Item1;  // 1
string str = tokens.Item2;  // "abc"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜