CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Sep 2012
    Posts
    1

    How to extract the numbers out a string.

    Hi, I am using a format like this: "xxx/xxx p:xxx" (xxx represents an integer number).
    How can I get the numbers seperatly?f.e: 450/45 p:33 How to extract the numbers 450,
    45 and 33 from the string. Who can help me? Greetings, Peter Kiers

  2. #2
    Join Date
    Sep 2012
    Posts
    10

    Re: How to extract the numbers out a string.

    You can use the Split( ) method: Overloaded. Identifies the substrings in the string that are delimited by one or more characters specified in an array, then places the substrings into a string array. string [ ] sn = sValue.Split(' '); foreach (string i in sn) Console.WriteLine(i);
    Or ToCharArray( ) method: char [ ] cArray = sValue.ToCharArray(0, 2); Console.WriteLine(cArray);

    Hope that helps.

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: How to extract the numbers out a string.

    Code:
    class Program
        {
            static void Main(string[] args)
            {
                var sb = new StringBuilder("450/45 p:33");
    
                sb.Replace('/', ' ');
                sb.Replace("p:", "");
    
                var index = 1;
    
                foreach (var s in sb.ToString().Split(new char[] { ' ' }))
                {
                    var value = Int32.Parse(s); // Not strickly necessary, but gives you value as Int type
                    Console.WriteLine(String.Format( "Number {0}: {1}", index++, value));
                }
            }
        }
    Outputs:
    Number 1: 450
    Number 2: 45
    Number 3: 33

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured