【问题标题】:How to get rid off of the punctuation in c spellchecking program?如何摆脱c拼写检查程序中的标点符号?
【发布时间】:2017-02-21 11:04:15
【问题描述】:
if(notfound == 1)
{
    int len = strlen(word);
    //if(strcmp(word, array)== 0)
    if(strcmp(array3,word)==0)
    {
        word[len - 1] = '\0';
    }
    if(strcmp(word, array2) ==0)
    {
        word[len - 1] = '\0';
    }

    fprintf(NewFile,"%s\n", word);
}

这是我的拼写检查程序代码,至少是给我带来大部分问题的部分。我的程序通过将其与 Dicitonary 进行比较,可以很好地对任何文本文件进行拼写检查。此代码中的单词保留在包含文本文件中错误单词的数组中。数组 3 是包含标点符号的单词数组,如下所示:char* array3[] = {"a.", "b.", "c.", "d.", "e.", "f.", "g.", "h."}; 我尝试将单词与此数组进行比较以消除标点符号(在本例中为点,但后来我计划其余的标点符号来处理)。问题是,如果我的数组看起来像“。”,“,”,“!”,“?”,“;”,strcmp 只是跳过它,而不是摆脱标点符号。而且我知道我的方法非常简单而且不是很合适,但是当我用“c.”尝试它时,它就起作用了。另外我对c语言很陌生

如果有人能够提供帮助,我将不胜感激,因为我已经被这个问题困扰了一个星期了

【问题讨论】:

  • 请开始缩进你的代码。
  • 不要把你的变量称为array3,而是一些重要的名字,比如punctuations
  • 代码太少,所以我们无法找出这里可能出现的问题。但是strcmp(array3, word) 看起来很可疑。打开编译器警告并将警告视为错误。
  • ... 并使用这样的数组:{"a.", "b.", "c.", "d.", ...}` 无论如何看起来都是非常糟糕的设计。
  • @xing 非常感谢你!我被这个东西困了一个星期!我知道这似乎既简单又愚蠢,但我对 C 完全陌生,我刚开始在 uni 中使用它,我发誓, strcspn 什么都没有。非常感谢你,再次感谢你:)

标签: c arrays spell-checking strcmp punctuation


【解决方案1】:

如果word 数组可能有一个尾随标点字符,则可以使用strcspn 删除该字符。
如果word 数组中有多个标点字符,则可以在循环中使用strpbrk 替换这些字符。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char word[100] = "";
    char punctuation[] = ",.!?;";
    char *temp = NULL;

    strcpy ( word, "text");//no punctuation
    printf ( "%s\n", word);
    word[strcspn ( word, punctuation)] = '\0';
    printf ( "%s\n", word);

    strcpy ( word, "comma,");
    printf ( "%s\n", word);
    word[strcspn ( word, punctuation)] = '\0';
    printf ( "%s\n", word);

    strcpy ( word, "period.");
    printf ( "%s\n", word);
    word[strcspn ( word, punctuation)] = '\0';
    printf ( "%s\n", word);

    strcpy ( word, "exclamation!");
    printf ( "%s\n", word);
    word[strcspn ( word, punctuation)] = '\0';
    printf ( "%s\n", word);

    strcpy ( word, "question?");
    printf ( "%s\n", word);
    word[strcspn ( word, punctuation)] = '\0';
    printf ( "%s\n", word);

    strcpy ( word, "semicolon;");
    printf ( "%s\n", word);
    word[strcspn ( word, punctuation)] = '\0';
    printf ( "%s\n", word);

    temp = word;
    strcpy ( word, "comma, period. exclamation! question? semicolon;");
    printf ( "%s\n", word);
    while ( ( temp = strpbrk ( temp, punctuation))) {//loop while punctuation is found
        *temp = ' ';//replace punctuation with space
    }
    printf ( "%s\n", word);

    return(0);
}

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2018-09-06
    • 2011-07-29
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多