简体   繁体   English

C 语言 strlen function 字符串中有换行符

[英]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?通常 C 语言中的 strlen() function 返回 unsigned int 但如果字符串有换行符,那么 output 会是什么? For example: What will be the output of strlen("stack\n") in C language?例如: C 语言中 strlen("stack\n") 的 output 将是什么?

strlen("stack\n") --> 6. Nothing special about '\n' . strlen("stack\n") --> 6. '\n'没什么特别的。

" What will be the output of strlen("stack\n") ? " " strlen("stack\n")的 output 是什么? "

6 . 6 . The newline character such as any character except '\0' (NUL) is counted as any character else.换行符,例如除'\0' (NUL) 之外的任何字符都被视为其他任何字符。

" Generally strlen() function in C language returns unsigned int . " 通常在 C 语言中的strlen() function 返回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 . strlen()返回一个size_t值,它与unsigned int完全不同,尽管在大多数实现中size_t可以是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数组中(它不是字符串文字并且具有不可变的内容)并且您想要删除换行符,则可以使用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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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