作者:chuntianhuaji | 来源:互联网 | 2022-11-25 11:19
为什么每个单词都进入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 "
还是,
?
1> Jonathan Lef..:
仔细看看这两行中的括号:
if((word[strlen(word - 1)] == ',')){
word[strlen(word) - 1] == '\0';
}
Here ^ ^
不对称是错误的.在单词开始之前开始搜索是未定义的行为.我认为,第二行是更接近正确的,但你需要替换==
与=
分配的新值(如所指出的paxdiablo在评论).此问题也会影响前一段代码.
if (word[strlen(word) - 1] == ',')
word[strlen(word) - 1] = '\0';
此外,您在技术上具有未定义的行为strncpy(word, word + 1, strlen(word));
- 源和目标数组不允许重叠(strncpy()
is 的正式原型char *strcat(char * restrict s1, const char * restrict s2);
,其中restrict
' s1
和'之间没有重叠s2
).使用memmove()
- 确实允许重叠副本 - 但是您需要知道字符串的长度并记住复制空字节,因此输出也是字符串.