c - 检查字符串中的特殊字符(在 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 ,
?
解决方案
仔细看看这两行中的括号:
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
之间没有重叠)。使用——这确实允许重叠副本——但你需要知道字符串有多长,并记住复制空字节,这样输出也是一个字符串。s1
s2
memmove()
推荐阅读
- reactjs - 是否可以将 Capacitor 集成到在单水疗中心(微前端架构)上运行的项目中?
- javascript - 从另一个文件添加到数组 - node.js
- flutter - 如何在轮播滑块的每张幻灯片上添加按钮
- go - Go 有没有办法用一个“go build”命令构建多个可执行文件?(和 Rust 一样)?
- hadoop-yarn - 如何让 apache yarn 支持新的应用类型?
- javascript - 从 JavaScript 网络应用程序读取苹果联系人
- php - 如何在 laravel 中使用多个过滤器
- python - 文本未附加到文本文件中
- reactjs - 为什么 expo cli 构建多次?
- flutter - 登录/注册后 Firebase 无限加载