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

I have lines that look like this:

1. abc
2. def
88. ghi

I would like to get numbers from strings and put them in a variable, and then get the rest of the string and put it in another variable. The number is always at the beginning of the line, and the number comes after the number. Is there an easy way so that I can parse one string into a number and a string?

+3
source share
5 answers

You can call IndexOfand Substring:

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

Not the best way, but split into a "." (thanks Kirk)

everything after that is a string, and everything before that will be a number.

+3
source
        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;
+1

:

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
}

, , .

int.Parse.

0
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

All Articles