繁体   English   中英

string1 中的 string2 计数在 C 中不起作用,但在 Python 中起作用

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

问题本身很简单。 我必须计算 s1 中 s2 的出现次数。 s2 的长度始终为 2。我尝试使用 C 来实现它,但即使我知道逻辑是正确的,它也不起作用。 所以我在 pyhton 中尝试了相同的逻辑,并且效果很好。 有人可以解释为什么吗? 还是我在 C 中做错了什么。 我在下面给出了两个代码。

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)

您的 python 代码实际上不正确,如果s1的最后一个字符与s2的第一个字符匹配,则会引发IndexError

您必须停止迭代s1的倒数第二个字符。

这是适用于任何长度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

首先,正如其他人指出的那样,您不想使用gets(),请尝试使用fgets()。 否则,您的逻辑是正确的,但是当您在输入中读取时,新行字符将包含在字符串中。

如果您要输入testes ,您的字符串将包含test\nes\n (两者分别包含 null 终止字节\0 )。 然后导致您在字符串test\n中搜索它找不到的 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ es\n 因此,您必须首先至少从要搜索的 substring 中删除换行符,您可以使用 strcspn() 为您提供es

一旦尾随换行符 (\n) 被替换为 null 终止字节。 您可以在字符串中搜索出现次数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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