简体   繁体   中英

Checking for specific characters in a String

I have a string that looks like this:

char *string = "This is a\r string\r\nTTTT";

Where I want to check a string (like the one above for the \\r and \\r\\n characters, however, simply using strcmp doesn't work. For instance:

if (strcmp(string, "\r\n") == 0) {     
    if (strcmp(string, "\n) == 0) {
        printf("The string contains both a newline, and "\r\n" characters");
    }
}

memcmp and strncmp don't seem to work either:

if (memcmp(string, "\r\n", 2) == 0) {
    if (memcmp(string, "\n", 1) == 0) {
        printf("The string contains both a newline, and "\r\n" characters");
    }
}

I also tried this (Which somewhat works, but then doesn't).

int i;
for (i = 0; i < strlen(string); i++) {
    if (string[i] == '\n') {
        if (strcmp(string, "\r\n") == 0) {
            printf("The string contains both a newline, and "\r\n" characters");
        }
    }
}

Where the lasted method I tried does indeed find the newline character, but fails to find the "\\r\\n" characters. And the other two above simply don't work at all, any ideas?

#include <stdio.h>
#include <string.h>

int main(void) {
    char * someString = "This is a\r string\r\nTTTT";
    if(strstr(someString, "\r\n") != NULL) {
        puts("We hit \\r\\n");
    }

    if(strstr(someString, "\n") != NULL) {
        puts("We hit \\n");
    }

    return 0;
}

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