Thread: search for chars

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    24

    Question search for chars

    How would you search for second occurence of the same character on the line? For example:

    ftp,tcp,SF,attack,smurf

    How would you search for 3rd comma (before attack) and save the word 'attack' in the buffer?

    ~Dmitry
    Dmitry Kashlev

  2. #2
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    Code:
    char searchThis[50]="ftp,tcp,SF,attack,smurf";//what to search through
    char * pointer=new char[500];//pointer with oversized buffer
    pointer=strstr(searchThis,"*,*,*,");//I think the wildcards should work, otherwise just do strstr three times for ","
    pointer[0]='\b';//deletes the comma returned in the pointer
    strtok(pointer,",");//deletes the comma after the word attack along with everything after it
    cout<<pointer<<endl;
    that should work as far as i know

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    With character arrays:
    Code:
       char str[80] = "ftp,tcp,SF,attack,smurf";
       char *p;
       char word[20] = "";
    
       p = strtok(str,",");
       p = strtok(NULL,",");
       p = strtok(NULL,",");
       p = strtok(NULL,",");
       cout << p << endl;
       strcpy(word,p);
       cout << "word:" << word << endl;
    Or it's easier with the string type. I don't use it (string type), but I think there is a find() function or something.

  4. #4
    Registered User
    Join Date
    Aug 2002
    Posts
    24
    all I get is segmentation fault. Any idea what this means?
    Dmitry Kashlev

  5. #5
    unregistered
    Guest
    Code:
    int comma;
    cout << "which comma do you want to find?" << endl;
    cin >> comma;
    
    int i;
    int commaCounter = 0;
    char input[] = "ftp,tcp,SF,attack,smurf";
    
    for(i = 0; i < strlen(input); i++)
    {
       if(input[i] == ',')
       {
          counter++;
            if(counter == comma)
            {
              cout << "we're there" << endl;
              cout << "comma number " << comma << " was found at character position " << i + 1 << " in the input ." << endl;
               i = strlen(input);
             }
        }
    }
    
    if(counter != comma)
      cout << "not that many commas in the input.  sorry....." << endl;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  2. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  3. Tutorial review
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 03-22-2004, 09:40 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM