How to convert string s="48727"; to int[]no={4,8,7,2,7};

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bilal Ameer

    How to convert string s="48727"; to int[]no={4,8,7,2,7};

    actually i need to convert string data (in which some numbers are given) into int array.
  • Bassem
    Contributor
    • Dec 2008
    • 344

    #2
    I don't think there is a built in Method in the .NET framework will completely do that. So, you will have to build one of your own.

    Code:
            public int[] ConvertStringIntoIntArray(string numberRepresenter)
            {
                List<int> arrayOfInt = new List<int>();
                foreach (char n in numberRepresenter)
                {
                    try
                    {
                        arrayOfInt.Add(n - '0');
                    }
                    catch { }
                }
                return arrayOfInt.ToArray();
            }
    Try to modify it to work better for your needs.

    Comment

    • Christian Binder
      Recognized Expert New Member
      • Jan 2008
      • 218

      #3
      Using LinQ, you could do the following
      Code:
      int[] no = (from ch in "48727" select ch - '0').ToArray();

      Comment

      • Bassem
        Contributor
        • Dec 2008
        • 344

        #4
        Christian Binder, excellent answer. Thanks, I learned something new :-)

        Comment

        • Curtis Rutland
          Recognized Expert Specialist
          • Apr 2008
          • 3264

          #5
          One of the beauties of LINQ is how many different ways there are to do something:

          Code:
          int[] nums = "12345".Select(x => int.Parse(x.ToString())).ToArray();

          Comment

          Working...