Fusako Hatasaka
Fusako Hatasaka

Reputation: 33

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 and a string?

Upvotes: 3

Views: 339

Answers (5)

Chris Fulstow
Chris Fulstow

Reputation: 41872

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"

Upvotes: 0

Alex Aza
Alex Aza

Reputation: 78447

        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;

Upvotes: 1

Adam Lear
Adam Lear

Reputation: 38768

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.

Upvotes: 0

soandos
soandos

Reputation: 5146

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.

Upvotes: 3

SLaks
SLaks

Reputation: 887275

You can call IndexOf and Substring:

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

Upvotes: 2

Related Questions