Checking for string contents? string Length Vs Empty String

前端 未结 13 901
野趣味
野趣味 2020-12-17 10:14

Which is more efficient for the compiler and the best practice for checking whether a string is blank?

  1. Checking whether the length of the string == 0
13条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 10:29

    In languages that use C-style (null-terminated) strings, comparing to "" will be faster

    Actually, it may be better to check if the first char in the string is '\0':

    char *mystring;
    /* do something with the string */
    if ((mystring != NULL) && (mystring[0] == '\0')) {
        /* the string is empty */
    }
    

    In Perl there's a third option, that the string is undefined. This is a bit different from a NULL pointer in C, if only because you don't get a segmentation fault for accessing an undefined string.

提交回复
热议问题