3

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?

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, but the delimiter should be . (dot-space). And the relevent function afterwards is int.Parse(string).
Who said anything about there possibly being two dots?
2

You can call IndexOf and Substring:

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

2 Comments

Thank you very much. Your solution looks easy to implement. One more quick question. I would like to convert num into a string with a leading zero. Is there an easy way to do that?
@Fusako: .ToString("000000"). See msdn.microsoft.com/en-us/library/dwhawy9k.aspx
1
        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;

2 Comments

Don't forget to backslash the first dot: (?<Number>\d+)\. (?<Text>.*)
@cxfx - Yes, bug. Thank you. Corrected the answer.
0

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.

Comments

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.