[英]checking if the characters in a string are either alphabets, numbers, or special characters. in c
[英]Checking for special characters in string (in 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';
}
沒有人有任何線索,為什么這樣的話認為他們的結局是一個"
或,
?
仔細看看這兩行中的括號:
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(word, word + 1, strlen(word));
—不允許源數組和目標數組重疊( strncpy()
的正式原型為char *strcat(char * restrict s1, const char * restrict s2);
其中restrict
表示' s1
和s2
之間無重疊)。 使用memmove()
(它允許重疊的副本),但是您需要知道字符串的長度,並記住復制空字節,因此輸出也是字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.