Thread: How to use "strstr" to find all occurrences of a substring in a string not only first

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    3

    How to use "strstr" to find all occurrences of a substring in a string not only first

    Hello guys.
    Im having troubles with the "strstr" function.

    Im trying to count the number of times a substring appears in a string.
    For this im using the STRSTR function but that function returns only the first occurrence of a substring in a string.

    So if I use STRSTR to count the number of times the word "par" appears in "parparpar" it will return 1 because after the first occurrence, the function stops.

    The code im using is this:

    Code:
    int countPar(char str[256])
    {
    int total;
    if (strstr(str, "par")!=NULL) // finds "par" in string
    total++;
    return total;    
    }
    That function always returns 1.

    I want it to return 3 if I use "parparpar" as str.

    All I want is to know the number of times a substring appears in a string.

    THANKS!!!!!!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    char *p = str;
    while ( strstr(p,"par") != NULL ) {
      p++; // can you improve this?
      total++;
    }

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    3
    Salem thanks but its not working, I tried your code but its not returning what it should.
    For the code below, it returns 4 instead of 2.

    Thanks for your help, waiting for more answers if possible.

    Code:
    int main()
    {
    int total=0;
    char *p="parpar";
    while ( strstr(p,"par") != NULL ) 
       {
    printf("%s", p); // to know the content of p
    p++;
    total++;
       }
    printf("%i", total);
    getch(); // pause
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    while ( (p=strstr(p,"par")) != NULL )

  5. #5
    Registered User
    Join Date
    Dec 2005
    Posts
    3
    It works now, perfectly.
    Full code:

    Code:
    int main()
    {
    char *p="parparpar";
    int total=0;
    while ( (p=strstr(p,"par")) != NULL )
      {
    total++;
    p++;
      }
    printf("%i", total); // prints 3 as it should
    getch();
    }
    Thanks for your help.

  6. #6
    template<typename T> threahdead's Avatar
    Join Date
    Sep 2002
    Posts
    214
    Quote Originally Posted by Salem
    Code:
    char *p = str;
    while ( strstr(p,"par") != NULL ) {
      p++; // can you improve this?
      total++;
    }
    Just an idea to improve this piece of code:
    Code:
    char *p = str;
    while ( strstr(p,"par") != NULL ) {
      p += strlen(p);
      total++;
    }

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Did you know p += strlen(p) always ends up pointing at the \0 ?

  8. #8
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Ok really bored:
    Code:
    #include <stdio.h>
    
    int main()
    {
            const char *haystack =
            "Is this the real life-\n"
            "Is this just fantasy-\n"
            "Caught in a landslide-\n"
            "No escape from reality-\n"
            "Open your eyes\n"
            "Look up to the skies and see-\n"
            "I.m just a poor boy,i need no sympathy-\n"
            "Because I.m easy come,easy go,\n"
            "A little high,little low,\n"
            "Anyway the wind blows,doesn.t really matter to me,\n"
            "To me\n"
            "Mama,just killed a man,\n"
            "Put a gun against his head,\n"
            "Pulled my trigger,now he.s dead,\n"
            "Mama,life had just begun,\n"
            "But now I.ve gone and thrown it all away-\n"
            "Mama ooo,\n"
            "Didn.t mean to make you cry-\n"
            "If I.m not back again this time tomorrow-\n"
            "Carry on,carry on,as if nothing really matters-\n"
            "Too late,my time has come,\n"
            "Sends shivers down my spine-\n"
            "Body.s aching all the time,\n"
            "Goodbye everybody-I.ve got to go-\n"
            "Gotta leave you all behind and face the truth-\n"
            "Mama ooo- (any way the wind blows)\n"
            "I don.t want to die,\n"
            "I sometimes wish I.d never been born at all-\n"
            "I see a little silhouetto of a man,\n"
            "Scaramouche,scaramouche will you do the fandango-\n"
            "Thunderbolt and lightning-very very frightening me-\n"
            "Galileo,galileo,\n"
            "Galileo galileo\n"
            "Galileo figaro-magnifico-\n"
            "But I.m just a poor boy and nobody loves me-\n"
            "He.s just a poor boy from a poor family-\n"
            "Spare him his life from this monstrosity-\n"
            "Easy come easy go-,will you let me go-\n"
            "Bismillah! no-,we will not let you go-let him go-\n"
            "Bismillah! we will not let you go-let him go\n"
            "Bismillah! we will not let you go-let me go\n"
            "Will not let you go-let me go\n"
            "Will not let you go let me go\n"
            "No,no,no,no,no,no,no-\n"
            "Mama mia,mama mia,mama mia let me go-\n"
            "Beelzebub has a devil put aside for me,for me,for me-\n"
            "So you think you can stone me and spit in my eye-\n"
            "So you think you can love me and leave me to die-\n"
            "Oh baby-can.t do this to me baby-\n"
            "Just gotta get out-just gotta get right outta here-\n"
            "Nothing really matters,\n"
            "Anyone can see,\n"
            "Nothing really matters-,nothing really matters to me,\n"
            "Any way the wind blows....";
            const char *needle = "poor";
            unsigned total = 0;
            const char *p = haystack;
            while ( (p=strstr(p,needle)) != NULL ) {
                    p += strlen(needle);
                    total++;
            }
            printf("%u occurences of %s\n", total, needle);
            return 0;
    }

  9. #9
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    How many occurences of "harhar" are in "harharharharharhar"?

  10. #10
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Quote Originally Posted by cwr
    How many occurences of "harhar" are in "harharharharharhar"?
    Even though that reply was meant to be trivial, it made me consider that some might say 3 and some might say 5.
    Sent from my iPadŽ

  11. #11
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Quote Originally Posted by SlyMaelstrom
    Even though that reply was meant to be trivial, it made me consider that some might say 3 and some might say 5.
    Yes, that was my point, and to illustrate the simple += strlen(needle) technique may produce unwanted results.

  12. #12
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Some might want to say there are 30 occurances of "harhar" in that string though. What I was saying was, what is considered undesired results to one person might be exactly what another person wanted. So long as you can make a reasonable explaination as to why your outcome came to be what it was, your program is valid. Of course if you were writing this for someone and they specified what is to be considered an occurance, then you're talking a different story.

    You're right though in making your point because it should be made clear that one way of writing a program might not be the best way or the expected way, even.
    Sent from my iPadŽ

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  3. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM