問題本身很簡單。我必須計算 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)
uj5u.com熱心網友回復:
您的 Python 代碼實際上是不正確的,IndexError如果的最后一個字符s1與s2.
您必須停止對 的倒數第二個字符進行迭代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)
輸出: 3
uj5u.com熱心網友回復:
首先,正如其他人指出的,您不想使用gets(),請嘗試使用fgets()。否則,您的邏輯是正確的,但是當您讀入輸入時,換行符將包含在字串中。
如果您要輸入testand es,您的字串將包含test\nand es\n(兩者分別包含空終止位元組\0)。然后導致您在字串中搜索它找不到test\n的子字串es\n。因此,您必須首先從至少要搜索的子字串中洗掉換行符,您可以使用 strcspn() 來為您提供es.
一旦尾隨換行符 (\n) 被替換為空終止位元組。您可以在字串中搜索出現的情況。
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369508.html
