none
Reading different types of values from a String - C#

    Question

  • How do you read different types of values from a string. E.g. This string can be {X=583,Y=20} or {X=13,Y=11} or {X=3,Y=370} or {X=103,Y=27}

    So, how do you read the value between Y= and } E.g. {X=583,Y=37} I want 37, but the number can be anything and not 37. Please help. This is a C# question

    The following code cannot help me to get exactly what I want. It can only give you what I want if I know the string length. I want to know the number between Y=  and }. E.g. {X=583,Y=37}.

    using System;
    using System.IO;
    
    public class CharsFromStr
    {
        public static void Main()
        {
            string str = "Some number of characters";
            char[] b = new char[str.Length];
    
            using (StringReader sr = new StringReader(str))
            {
                // Read 13 characters from the string into the array.
                sr.Read(b, 0, 13);
                Console.WriteLine(b);
    
                // Read the rest of the string starting at the current string position.
                // Put in the array starting at the 6th array member.
                sr.Read(b, 5, str.Length - 13);
                Console.WriteLine(b);
            }
        }
    }
    // The example has the following output:
    //
    // Some number o
    // Some f characters
    
    

    Wednesday, April 26, 2017 2:09 PM

Answers

  • I found an answer! And that was to use index of from location where I wanted begin the search, and the index of where I wanted to end the search on a new string. Then you deduct the two to get a precise, and sharp result. I've really become good in programming these days. I hope you're happy for me too

                string str = "{X=53,Y=37}";
    
                int start = str.IndexOf("Y=") + 2;
                int end = str.IndexOf("}", start);
                string result = str.Substring(start, end - start);
    


    Wednesday, April 26, 2017 2:38 PM

All replies

  • I found an answer! And that was to use index of from location where I wanted begin the search, and the index of where I wanted to end the search on a new string. Then you deduct the two to get a precise, and sharp result. I've really become good in programming these days. I hope you're happy for me too

                string str = "{X=53,Y=37}";
    
                int start = str.IndexOf("Y=") + 2;
                int end = str.IndexOf("}", start);
                string result = str.Substring(start, end - start);
    


    Wednesday, April 26, 2017 2:38 PM
  • But how would you search for something between Y= and } on the last column of the list below?

    {X=2728,Y=0}

    {X=4743,Y=1}

    {X=636,Y=3}

    {X=12,Y=290292}

    {X=3,Y=8299}

    {X=70,Y=27}

    {X=5,Y=927}

    This last item is the one I would like to search using the code on the question.


    Wednesday, April 26, 2017 2:48 PM