在 C 中识别字符 '

identifying char ' in C

我可能正在以糟糕的方式实现此代码,但我目前正在执行 CS50 并尝试在我的字符串中搜索 char '.我搜索了其他字符,例如 text [i] == '!' 但是在执行 text [i] == ''' 时它无法正常工作。有没有可能让它以这种方式工作?

如果你感兴趣的话,这是我的糟糕代码...我正在尝试查找字母、单词和句子的数量。除了我无法定义的字符外,它还有效。

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main (void)
{
string text = get_string("Input text: "); //accept text input
int i;
int length = strlen(text);
int count = 0;
int count2 = 0;
int count3 = 0;
int excludeothers = (length - count);

for (i = 0; i < length; i++)
{
    if(text[i] == ' ' || text [i] == '!' || text[i] == '?' || text[i] == '.' || text[i] == ',' || text[i] == '"' || text[i] == ':' || text[i] == ';' || text[i] == '-' || text[i] == ''') //check number of letters
    {
        count++;
    }
}

for (i = 0; i <= length; i++)
{
    if((text[i] == ' ' || text[i] == '[=10=]') && (text[i-1] != ' ' || text[i-1] != '[=10=]')) //check number of words
    {
        count2++;
    }
}

for (i = 0; i < length; i++)
{
    if((text[i] == '.' || text[i] == '?' || text [i] == '!') && (text[i+1] == ' ' || text[i+1] == '[=10=]')) //check number of sentences
    {
        count3++;
    }
}


    printf("%i letters\n", excludeothers); //print letters
    printf("%i words\n", count2); //print words
    printf("%i sentences\n", count3); //print sentences

}

你需要转义它:

'\''

这意味着单引号字符。同样的方法,你可以在字符串中使用双引号:"\""

进一步阅读:https://en.wikipedia.org/wiki/Escape_sequences_in_C

如果你想按照自己的方式去做,那么,是的,你需要转义那个角色。看一下 GeeksForGeeks 关于一般转义字符的文章。它将帮助您了解哪些可以作为普通字符传递,哪些需要在它们前面加一个反斜杠。

但是,如果您正在考虑其他选择,请查看 strchr()。它是您可以使用的内置函数。使用它会大大改进和简化您的代码。你可以看看this question discussion for more information. And here is a reference for C documentation这个函数。