简体   繁体   中英

C language strlen function with new line character in the string

Generally strlen() function in C language returns unsigned int but if the string has new line character then what will be the output? For example: What will be the output of strlen("stack\n") in C language?

strlen("stack\n") --> 6. Nothing special about '\n' .

" What will be the output of strlen("stack\n") ? "

6 . The newline character such as any character except '\0' (NUL) is counted as any character else.

" Generally strlen() function in C language returns unsigned int . "

That is not correct. strlen() returns a size_t value which is quite a distinct type from unsigned int , although in most implementations size_t can be an alias for unsigned int . But to keep the difference is important.


Note: If the string is stored in an char array instead (it is not a string literal and with that immutable) and you want to remove the newline, you can use strcspn() :

char a[7] = "stack\n";        // 7 elements, not 6. Required to store terminating NUL.

printf("%zu\n", strlen(a));   // This will print 6.

a[strcspn(a, "\n")] = 0;      // Replace newline with NUL.

printf("%zu", strlen(a));     // This will print 5.

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