home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / string4.cpp < prev    next >
C/C++ Source or Header  |  1993-03-29  |  1KB  |  55 lines

  1. /*
  2.   C++ program that demonstrates searching for
  3.   characters and strings
  4. */
  5.  
  6. #include <iostream.h>                   
  7. #include <string.h>
  8.  
  9. const unsigned STR_SIZE = 40;
  10.  
  11. main()
  12. {
  13.     char mainStr[STR_SIZE+1];
  14.     char subStr[STR_SIZE+1];
  15.     char findChar;
  16.     char *p;                    
  17.     int index;
  18.     int count;
  19.     
  20.     cout << "Enter a string : ";
  21.     cin.getline(mainStr, STR_SIZE);
  22.     cout << "Enter a search string : ";
  23.     cin.getline(subStr, STR_SIZE);
  24.     cout << "Enter a search character : ";
  25.     cin >> findChar;
  26.     
  27.     cout << "          1         2         3         4\n";
  28.     cout << "01234567890123456789012345678901234567890\n";
  29.     cout << mainStr << "\n";
  30.     cout << "Searching for string " << subStr << "\n";
  31.     p = strstr(mainStr, subStr);
  32.     count = 0;
  33.     while (p) { 
  34.       count++;
  35.       index = p - mainStr;
  36.       cout << "Match at index " << index << "\n";
  37.       p = strstr(++p, subStr);
  38.     }         
  39.     if (count == 0)
  40.       cout << "No match for substring in main string\n";            
  41.     
  42.     cout << "Searching for character " << findChar << "\n";
  43.     p = strchr(mainStr, findChar);              
  44.     count = 0;
  45.     while (p) {
  46.       count++;
  47.       index = p - mainStr;
  48.       cout << "Match at index " << index << "\n";
  49.       p = strchr(++p, findChar);
  50.     }                     
  51.     if (count == 0)
  52.       cout << "No match for search character in main string\n";            
  53.     return 0;
  54. }
  55.