[英]Count the Occurrences of a Substring in String
My program is supposed to count in a string an entered string.我的程序应该在一个字符串中计算一个输入的字符串。
For example:例如:
Enter a text: Hello World
Enter a string: llo
occurs 1 times in Hello World
Unfortunately, my program does not give me anything.不幸的是,我的程序没有给我任何东西。 Does anyone have a tip for me?
有人给我小费吗?
void aufgabe7(char string[MAX], char stringw[MAX]){
printf("Enter a Text: \n");
fgets(string, MAX, stdin);
int i, j, len, len2;
int count = 0;
int count2 = 0;
len = strlen(string);
printf("Enter a string: \n");
fgets(stringw, MAX, stdin);
len2 = strlen(stringw);
for (i = 0; i < len;)
{
j = 0;
count = 0;
while ((string[i] == stringw[j]))
{
count++;
i++;
j++;
}
if (count == len2)
{
count2++;
count = 0;
}
else
i++;
}
printf("%s occurs %d times in %s \n", stringw, count2, string);
}
void main (void){
char data[MAX];
task7(&data[0], &data[0]);
}
As commenter @Steve Summit noted, you are searching for a string read from fgets
, which has a trailing newline.正如评论者@Steve Summit 指出的那样,您正在搜索从
fgets
读取的字符串,它有一个尾随换行符。 Normally, you would need to remove the newline from the input from fgets
, otherwise it is part of the searched for string.通常,您需要从
fgets
的输入中删除换行符,否则它是搜索字符串的一部分。 The simplest way to do this is to call buffer[strcspn(buffer, "\n")] = '\0';
最简单的方法是调用
buffer[strcspn(buffer, "\n")] = '\0';
as documented in this question .如本问题所述。
However, I feel the correct answer to this question is that there is a more idiomatic way of doing this with C than comparing char
by char
: using strstr
with pointer arithmetic will work just as well and is cleaner to read:但是,我觉得这个问题的正确答案是,使用 C 比按
char
比较char
有一种更惯用的方法:将strstr
与指针算法一起使用同样有效,并且阅读起来更清晰:
char input[SIZE];
char search[SIZE];
size_t count = 0;
printf("Enter a phrase: ");
fgets(input, SIZE, stdin);
input[strcspn(input, "\n")] = '\0';
printf("\nEnter a sub-phrase: ");
fgets(search, SIZE, stdin);
search[strcspn(search, "\n")] = '\0';
char *p = input;
while((p = strstr(p, search)) != NULL)
{
printf("Found occurrence of '%s' at position %td\n", search, (ptrdiff_t)(p - input));
count++;
p++;
}
printf("Found %zu occurrences of '%s'.\n", count, search);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.