c - 通过字符索引对文本中的单词进行索引。(C)
问题描述
目前正在做一个简短的任务,给定一个单词,我必须通过字符索引打印出这些单词的位置。在 C 中尝试这样做。目前正在尝试解决一个问题,如果单词:'it' 是输入,'it' 和 'fit' 将被视为它的两次出现。通过跟踪前面的字符来修复它,例如 (it)alics。无法向后复制。任何帮助是极大的赞赏。
代码:
void compareWord(char word[], int size){
char c;
int index = -1; //Assuming we want first char index in text to be 0.
char spaceCheck = ' ';
while ((c = getchar()) != EOF) {
index++;
if (c == word[0]) {
char storing = c;
char otherWord[size];
otherWord[0] = c;
for (int i = 1; i < size ; i++) {
otherWord[i] = (storing = getchar());
index++;
}
if (((storing = getchar()) == ' ' ) || (storing == '\n') && (strcmp(word, otherWord) == 0)) {
index++;
int wordIndex = index;
wordIndex -= size;
printf("%d \n", wordIndex);
} else
index++;
}
spaceCheck = c;
}
}
int main() {
char word[] = "it";
compareWord(word, 2);
}
变量“spaceCheck”是我试图检查单词之前的字符是否为空格。以前
(spaceCheck == ' ' )
在长 if 语句中,没有工作。
解决方案
您说问题是找不到嵌入的单词匹配,
建议使用功能:strstr()
搜索嵌入词
strstr()
通过头文件公开:string.h
完整的语法:
char *strstr(const char *haystack, const char *needle);
描述:“strstr() 函数在字符串 haystack 中找到第一次出现的子字符串 needle。不比较终止的空字节 ('\0')。”
返回值:“这些函数返回一个指向已定位子字符串开头的指针,如果未找到子字符串,则返回 NULL。”
推荐阅读
- c# - 如何在统一 2d 中创建随机生成器?
- vue.js - 如何在 vuetify 中构建项目?
- php - PHP gettext 翻译没有被拾取
- algorithm - 下面算法的时间复杂度是多少?
- java - 在 java 中创建事件时在 ICAL 日历中获取日历 ID
- javascript - 将字符串传递给事件侦听器函数
- amazon-web-services - Fargate 中的 StartTask V/S RunTask
- java - 为什么当 Comparator.compare 相等时我们需要返回 0
- node.js - 使用 DataDog 的舵图集成 DataDog GKE NESTJS
- c++ - 错误:运算符 [] 不匹配。在将 int 与列表中的 int 进行比较时
,