首页 > 解决方案 > 检查字符串中的特殊字符(在 C 中)

问题描述

为什么每个单词都进入 if 语句检查字符串是否以 ',' 结尾,以及检查它是否以 '"' 结尾。

我看到这样的词:

"held"
"hand"
"bond"
"like"
"was"
"her"
"familliar"

(以上所有只是输入 if 语句的单词示例

void RemoveOddSigns(char *word){

    if(word[0] == '"'){
        strncpy(word, word + 1, strlen(word));
    }

    if(word[strlen(word - 1)] == '"'){
        word[strlen(word) - 1] == '\0';
    }

    if((word[strlen(word - 1)] == ',')){
        word[strlen(word) - 1] == '\0';
    }

有谁知道为什么这些词认为它们的结尾是 a"或 a ,

标签: c

解决方案


仔细看看这两行中的括号:

if((word[strlen(word - 1)] == ',')){
    word[strlen(word) - 1] == '\0';
}
           Here    ^   ^

不对称是错误的。在单词开始之前开始搜索是未定义的行为。我认为第二行更接近正确,但是您需要替换==with来分配新值(正如paxdiablo评论=中指出的那样)。这个问题也影响了前面一段代码。

if (word[strlen(word) - 1] == ',')
    word[strlen(word) - 1] = '\0';

此外,您在技术上具有未定义strncpy(word, word + 1, strlen(word));的行为 - 源数组和目标数组不允许重叠(的正式原型strncpy()char *strcat(char * restrict s1, const char * restrict s2);,其中的意思是“和restrict之间没有重叠)。使用——这确实允许重叠副本——但你需要知道字符串有多长,并记住复制空字节,这样输出也是一个字符串。s1s2memmove()


推荐阅读