1

A friend of mine needed help counting the occurrences of a substring in a string, and I came up with the following code. Does anyone know a better method to do this?

#include "stdio.h"
#include "string.h"

int main(int argc, char *argv[])
{
    char str1[50], str2[50];
    int i, j, l1, l2, match, count;

    printf("String 1:\n");
    gets(str2);
    printf("String 2:\n");
    gets(str1);

    l1 = strlen(str1);
    l2 = strlen(str2);

    count = 0;

    for(i = 0; i < l1; i++)
    {
        match = 0;
        for(j = 0; j < l2; j++)
        {
            if(str1[i + j] == str2[j])
            {
                match++;
            }
        }

        if(match == l2)
        {
            count++;
        }
    }

    printf("Substrings: %d\n", count);
}
5
  • Why don't you make your homework yourself? Commented Sep 30, 2011 at 14:27
  • LOL it's not my homework, and you can see I've already done it... I was just looking for a better solution. Commented Sep 30, 2011 at 14:36
  • Use #include <stdio.h> with angle brackets instead of quotes; it's what the standard says you should do. Although the quotes work, they're aconventional. Commented Sep 30, 2011 at 14:46
  • Thanks for the info, but I only changed them here because StackOverflow wasn't showing them in its WYSIWYG editor. :) Commented Sep 30, 2011 at 14:55
  • How many times does "aba" exist in "abababa"? Commented Sep 30, 2011 at 15:19

5 Answers 5

4

how about this: (using the strstr function, reference here)

int count = 0;
char str1[50], str2[50];
char* tmp = str1;
int count;

printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);

while(*tmp != '\0' && (tmp = strstr(tmp, str2))) {
    ++count;
    ++tmp;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It worked flawlessly. I already knew strstr, but I did not realize how to use its return value. Simple and efficient solution, thanks!
I think you're missing a parenthesis in that while definition that encloses tmp = strstr(tmp, str2). This answer helped me a lot, thank you.
3

Please do not use or encourage the use of gets. Beyond the fact that it will introduce a point of failure in your code, it has been deprecated as of C99 and will be gone completely from C1X.

As others have said, strstr is your friend here:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char s1[50], s2[50];
  char *p;
  size_t count = 0;
  size_t len1;

  printf("Gimme a string: ");
  fflush(stdout);
  fgets(s1, sizeof s1, stdin);
  p = strchr(s1, '\n');          // get rid of the trailing newline
  if (p)
    *p = 0;

  printf("Gimme another string: ");
  fflush(stdout);
  fgets(s2, sizeof s2, stdin);
  p = strchr(s2, '\n');          // get rid of the trailing newline
  if (p)
    *p = 0;

  p = s2;
  len1 = strlen(s1);

  while ((p = strstr(p, s1)) != NULL && p != s1)
  {
    count++;
    p += len1;
  }

  printf("Found %lu occurrences of %s in %s\n", count, s1, s2);
  return 0;
}

3 Comments

Good point about not using gets(). Although it will not be standard in C1X, it will (sadly) be present in C libraries for another decade or three for reasons of backwards incompatibility. Personally, I think the correct implementation is char *gets(char *buffer) { abort(); return 0; } (where the return is optional if the compiler knows that abort() does not return).
Thanks for the info mate. GCC always complains about gets(), so I guess I'll try to get acquainted to fgets() hehe. Just a simple question: are all those fflush's really needed?
Standard output is (normally) buffered, so if you write a string without a terminating newline, it may not show up on the console without an explicit flush.
0

You might want to take a look at the strstr function (if you're not already familiar with it).

2 Comments

I don't think that this function is defined in the C standard. I guess it is only available in non-standard extensions.
You're right. Changed my post from "instr" to "strstr". Thanks.
0
int main()
  {
          char *str = "This is demo";
          char *sub = "is";
          int i,j,count;
          i=j=count=0;
          while(str[i]!='\0')
          {
           if (str[i] == sub[j] && str[i+1] == sub[j+1])
          {
                  count++;
          }
          i++;
          }
          cout<<count;
          return 0;
  }

Above code works but this is static.

Comments

0

You can use QString in QT library

QString t = "yourstring";
t.count("yoursubstring");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.