How to count how many substrings are in a string in C? [duplicate]

0

link

This exercise I thought it best to read as string or not ...

#include <stdio.h>

int main(void) {
char N1,quantidadesdeN1;

while(scanf("%s",&N1)!=EOF)
   {
     scanf("%s",&quantidadesdeN1);

     /*Como faço pra ver quantos N1 tem na variável quantidadesdeN1 com strcmp ?No strcmp tem jeito de pegar apenas partes da quantidadedeN1? Se caso não for possível resolver no strcmp tem outro jeito de resolver ?
     */
   }
return 0;
} 
    
asked by anonymous 13.08.2018 / 19:08

2 answers

0

In the library you have a function called strncmp (str1, str2, case_number)

str1 = > variable 1 str2 = > variable 2 number of cases = > you place as many houses as you want for comparison.

Put the function into a loop repeat, which changes the initial position of str2, a count variable for the times str1 was encountered, and finally a variable for first position

link

    
13.08.2018 / 19:26
0

You can use the strstr () function, this function checks for a substring in a string, then just count the number of characters in the substring compared to the string, or the strncmp ()

If it is to check only from the beginning, Ex:

112
1125468

In this case, you can loop through the character, if it is different, give break and conclude that it is not a Subsequence

It will also be necessary to allocate memory of 10^10 and 10^32 in the 2 strings, as requested by the exercise.

Code :

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

int main(void)
{
    char N1[100], N2[100];
    int count=0, x=0;

    scanf(" %s",N1);
    scanf(" %s", N2);
    do
    {
        if(!strncmp(N2+x, N1, strlen(N1)))
        {
            count++;
            printf("N1 e´ uma substring de N2\n");
            printf("Qtd.Subsequencias %d\n", count);
            x+=strlen(N1);
        }
        else
            x+=1;
    }    while(x<strlen(N2));

}

I think this is what you want to do, of course we have to take the prints in the loop, but that's just an example

STDIN

12
123123123123

STDOUT

N1 e´ uma substring de N2
Qtd.Subsequencias 4

As we can see, in the last iteration Qtd.Subsequencias equals 4. In this case the quickest way would be to use the strncmp ()

    
13.08.2018 / 19:13