简体   繁体   中英

Checking for special characters in string (in C)

Why does every word go into the if statement checking whether the string ends with a ',' and the one checking whether it ends with a '"'.

I see words like:

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

(all of the above is just examples of words that enters the if statements

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';
    }

Does anyone have any clue why such words think their ending is a " or a , ?

Look hard at the parentheses in these two lines:

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

The asymmetry is wrong. Starting your search before the word starts is undefined behaviour. I think the second line is more nearly correct, but you need to replace the == with = to assign the new value (as pointed out by paxdiablo in a comment ). This problem also affects the previous paragraph of code.

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

Also, you technically have undefined behaviour with strncpy(word, word + 1, strlen(word)); — the source and target arrays are not allowed to overlap (the formal prototype for strncpy() is char *strcat(char * restrict s1, const char * restrict s2); , where the restrict means 'no overlap between s1 and s2 ). Use memmove() — that does allow overlapping copies — but you'll need to know how long the string is and remember to copy the null byte so the output is a string too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM