1

Suppose I've strings like below:

  1. _4_5
  2. _15_16

Now I want them to separate and get the values in variables like

  1. i=4, j=5
  2. i=15, j=16

How it could be done?

1

2 Answers 2

3

Split the string by underscores and pull out the parts:

string s = "_4_5";
string[] parts = s.Split(new [] {'_'},StringSplitOptions.RemoveEmptyEntries);
i = int.Parse(parts[0]);
j = int.Parse(parts[1]);

Some things to add:

  • error handling
  • bounds checking (did I get two parts back?)
  • number checking using TryParse (are the parts really numbers?)
Sign up to request clarification or add additional context in comments.

Comments

1

In addition to D Stanley's answer, if you are going to have an unknown number of variables (in other words, not just i or j), you could use this method:

class Program
{
    static void Main(string[] args)
    {
        string s = "_8_12";

        Console.WriteLine("Original ==> \"{0}\"", s);
        Dictionary<string, int> numbers = ParseNumbers(s);
        PrintNumbers(numbers);
        s = "_1_19_7";
        Console.WriteLine("Original ==> \"{0}\"", s);
        numbers = ParseNumbers(s);
        PrintNumbers(numbers);
    }

    private static Dictionary<string, int> ParseNumbers(string s)
    {
        var variables = new Dictionary<string, int>();
        char startVar = 'i'; // Start at 'i' Variable

        string[] nums = s.Split('_');

        foreach (string num in nums)
        {
            if (string.IsNullOrWhiteSpace(num))
                continue;
            variables.Add(startVar.ToString(CultureInfo.InvariantCulture), int.Parse(num));
            startVar++;
        }
        return variables;
    }

    private static void PrintNumbers(Dictionary<string, int> numbers)
    {
        foreach (var q in numbers)
        {
            Console.WriteLine("{0} ==> {1}", q.Key, q.Value);
        }

        Console.WriteLine();
    }
}

This will allow you to have more than just 2 numbers per input line. So you can pass in strings like _8_12 or _8_12_13_19_25 or even just _8.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.