首页 > 解决方案 > 通过字符索引对文本中的单词进行索引。(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 语句中,没有工作。

标签: cindexing

解决方案


您说问题是找不到嵌入的单词匹配,

建议使用功能:strstr()搜索嵌入词

strstr()通过头文件公开:string.h

完整的语法:

char *strstr(const char *haystack, const char *needle);

描述:“strstr() 函数在字符串 haystack 中找到第一次出现的子字符串 needle。不比较终止的空字节 ('\0')。”

返回值:“这些函数返回一个指向已定位子字符串开头的指针,如果未找到子字符串,则返回 NULL。”


推荐阅读