Thread: finding an integer in an integer

  1. #1
    Unregistered
    Guest

    finding an integer in an integer

    is there any way to search for the occurence of an integer inside an iteger? ie. to try to find '2' in '12' ?

    Thanks

  2. #2
    I'm Back
    Join Date
    Dec 2001
    Posts
    556
    you could copy that integer to a char and then search.

    I dont know of any direct method.
    -

  3. #3
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    You could use itoa to convert the integer to a string and then search for the digit. Ofcourse also the digit must be converted to a string.

  4. #4
    Unregistered
    Guest
    Thanks for that, Shiro, but would you be able to give me a code example of how to use that function and then search for it? Thanks. I really apprieciate it, mate.

    Thanks

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Code:
    #include <iostream>
    #include <sstream>
    const char match = '2';
    
    int main ( void )
    {
      int x = 12, count = 0;
      std::ostringstream oss;
      oss<<x;
      std::string s = oss.str();
      for ( int i = 0; i < s.length(); i++ )
        if ( s[i] == match ) count++;
      std::cout<< count <<" digit(s) match \'"<< match <<"\'\n";
      return 0;
    }
    or
    Code:
    #include <iostream>
    const char match = '2';
    
    int main ( void )
    {
      int x = 12, count = 0;
      char buf[BUFSIZ] = {'\0'};
      sprintf ( buf, "%d", x );
      for ( int i = 0; i < strlen ( buf ); i++ )
        if ( buf[i] == match ) count++;
      std::cout<< count <<" digit(s) match \'"<< match <<"\'\n";
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Jan 2002
    Posts
    552
    or you could use the direct method...
    Code:
    int main()
    {
       int x = 1232, count = 0, target = 2;
       while (x) {
           if (x % 10 == target)
               count++;
           x /= 10;
       }
       ...
    }
    Last edited by *ClownPimp*; 05-09-2002 at 07:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 22
    Last Post: 05-29-2009, 05:44 PM
  2. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  3. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  4. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  5. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM