开发者

How can I parse integer from a user provided string

开发者 https://www.devze.com 2023-03-15 02:36 出处:网络
I have a specification where the user needs to type in a string of pair of co-ordinates like: {{2,3}, {9,0}}

I have a specification where the user needs to type in a string of pair of co-ordinates like:

{{2,3}, {9,0}}

these are 开发者_JAVA百科the co-ordinates of a line on a 2-D axis.

I want to parse this user-input string during runtime dynamically in C# and enter these co-ordinates in a 2-D array. I know we can do hard-coded:

int[,] CoOrdinates = {{2,3}, {9,0}};

but I do not know how to get the user to type in a string and get the co-ordinates from the string to store in the array dynamically.

I'm using Console.Readline(); to get the user to input the co-ordinates.

Please help, thanks!


I would use a regular expression (Regex class in C#) to parse out the bits of the string you want, and then Int32.TryParse() to convert the string to a number. This is a good resource for constructing regular expressions, and this is my preferred regex tester. Good luck.


A quick answer:

    public void IntegerReader()
    {
        string integers = Console.ReadLine();

        string[] split = integers.Split(',');

        int result;

        foreach (string s in split)
        {
            if (!string.IsNullOrEmpty(s.Trim()))
                if (int.TryParse(s.Trim(), out result))
                    Console.WriteLine(result);
        }
    }


This isn't super elegant but I think the result is what you expect

string coords = "{{2,3}, {9,0}}";
string matchPattern = @"\{\{(?<x1>\d{1})\,(?<y1>\d{1})\}\,\s*\{(?<x2>\d{1})\,(?<y2>\d{1})\}\}";

var matches = Regex.Match(coords, matchPattern);

int[,] values = new int[2,2];

int.TryParse(matches.Groups["x1"].ToString(), out values[0,0]);
int.TryParse(matches.Groups["y1"].ToString(), out values[0,1]);

int.TryParse(matches.Groups["x2"].ToString(), out values[1,0]);
int.TryParse(matches.Groups["y2"].ToString(), out values[1,1]);

/* Result:
 *    0  1
 *   -----
 * 0| 2  3
 * 1| 9  0
 */

Of course you will want to check that four groups were returned before assigning values to the rectangular array, but that should be easy enough for you to implement.


            string s = "{{2,3}, {9,0}}";
            string p = "{(?<x>\\d),(?<y>\\d)}";
            Regex regex = new Regex(p);
            MatchCollection ms = regex.Matches(s);
            int[,] cood = new int[ms.Count, ms.Count];
            int i =0;
            foreach (Match m in ms)
            {
                cood[i,0] = int.Parse(m.Groups["x"].Value);
                cood[i, 1] = int.Parse(m.Groups["y"].Value);
                i++;
            }

You can use TryParse if wrong value in coordinates is expected

0

精彩评论

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