Home > Software engineering >  Count of string2 in string1 not working in C, but works in Python
Count of string2 in string1 not working in C, but works in Python

Time:11-30

The problem itself is simple. I have to count the number of occurence of s2 in s1. And length of s2 is always 2. I tried to implement it with C, but it did not work even though i know the logic is correct. So i tried the same logic in pyhton and it works perfectly. Can someone explain why? Or did i do anything wrong in C. I given both codes below.

C

#include<stdio.h>
#include<string.h>
int main()
{
char s1[100],s2[2];
int count = 0;
gets(s1);
gets(s2);
for(int i=0;i<strlen(s1);i  )
{
    if(s1[i] == s2[0] && s1[i 1] == s2[1])
    {
        count  ;
    }
}
printf("%d",count);
return 0;
}

Python

s1 = input()
s2 = input()
count = 0
for i in range(0,len(s1)):
    if(s1[i] == s2[0] and s1[i 1] == s2[1]):
        count = count 1
print(count)

CodePudding user response:

Your python code is actually incorrect, it would raise an IndexError if the last character of s1 matches the first of s2.

You have to stop iterating on the second to last character of s1.

Here is a generic solution working for any length of s2:

s1 = 'abaccabaabaccca'
s2 = 'aba'
count = 0
for i in range(len(s1)-len(s2) 1):
    if s2 == s1[i:i len(s2)]:
        count  = 1
print(count)

output: 3

CodePudding user response:

First, as others have pointed out, you do not want to use gets(), try using fgets(). Otherwise, your logic is correct but you need to read in the input, and then remove the trailing newline (\n) and replace it with a null terminating byte. After that is said

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

int main() {
    char s1[100], s2[4];
    int count = 0;
    fgets(s1, 99, stdin);
    fgets(s2, 3, stdin);
    s1[strcspn(s1, "\n")] = '\0';
    s2[strcspn(s2, "\n")] = '\0';

    for(int i=0;i < strlen(s1) - 1;i  ) {
        if(s1[i] == s2[0] && s1[i 1] == s2[1]) {
            count  ;
        }
    }

    printf("%d\n",count);
    return 0;
}
  • Related