简体   繁体   中英

Count of string2 in string1 not working in C, but works in Python

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)

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

First, as others have pointed out, you do not want to use gets(), try using fgets(). Otherwise, your logic is correct but when you read in the input, the new line character will be included in the string.

If you were to input test and es , your strings will contain test\n and es\n (with both respectively containing the null terminating byte \0 ). Then leads to you searching the string test\n for the substring es\n which it will not find. So you must first remove the new line character from, at least, the substring you want to search for which you can do with strcspn() to give you es .

Once the trailing newline (\n) has been replaced with a null terminating byte. You can search the string for occurances.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM