c - 当没有子字符串时,K&R 的几乎相似的 strindex 实现找到了子字符串
问题描述
我试图实现 K&R strindex 程序。将要求用户输入一行,如果该行包含字符串“boi”,程序将确认该行包含该模式。问题是,程序确认了其他一些字符串/字符串。
如果我输入“şgb”,它将确认它包含字符串“boi”。到目前为止,它只发生在“şgb”上。
https://onlinegdb.com/SyeeO0mzH
#include <stdio.h>
#define MAXLINE_LENGTH 100
char pattern[] = "boi";
int get_line(char line[], int maxlength);
int str_index(char str[], char substr[]);
int main() {
char line[MAXLINE_LENGTH];
while(get_line(line, MAXLINE_LENGTH) > 0) {
if(str_index(line, pattern) >= 0) {
printf("%s", line);
printf("Pattern found above line\n");
}
}
return 0;
}
int get_line(char line[], int maxlength){
int index = 0, character;
while(--maxlength > 0 && (character = getchar()) != EOF && character != '\n') {
line[index++] = character;
}
if(character == '\n') {
line[index++] = character;
}
line[index] = '\0';
return index;
}
int str_index(char str[], char substr[]) {
int i, j, k;
for(i = 0; str[i] != '\0'; i++) {
for(j = i, k = 0; substr[k] != '\0' && str[j] == substr[k]; j++, k++) ;
if(k > 0) {
return i;
}
}
return -1;
}
boi
boi
Pattern found above line
fbajdobadşgbadf
fbajdobadşgbadf
Pattern found above line
şgb
şgb
Pattern found above line
解决方案
推荐阅读
- angular - 运行业力单元测试用例“引发未知 [对象对象]”时出错
- python - 我的时间序列图如何从“00:00”开始并在“23:00”结束?两边没有空格
- asp.net-mvc - 在 Bamboo 中设置 NSIS 构建
- java - 从另一个类调用时函数崩溃应用程序但从 MainActivity.java 调用时不会
- python - 如何用 Python 重新排列一个复杂的方程
- tensorflow - 视频对象分类建议
- highcharts - HIghchart Treemap - 在图例单击时添加双击事件
- android - 获取所有画廊图像并在 android 应用程序中显示
- postcss - PostCSS 自定义插件 - TypeError:无法读取未定义的属性“_autoprefixerPrefix”
- android - 如何使用 wifi 网络在 android 手机和 pc 上的网络浏览器之间建立网络连接?