繁体   English   中英

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

[英]C language strlen function with new line character in the string

通常 C 语言中的 strlen() function 返回 unsigned int 但如果字符串有换行符,那么 output 会是什么? 例如: C 语言中 strlen("stack\n") 的 output 将是什么?

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

" strlen("stack\n")的 output 是什么? "

6 . 换行符,例如除'\0' (NUL) 之外的任何字符都被视为其他任何字符。

通常在 C 语言中的strlen() function 返回unsigned int

这是不正确的。 strlen()返回一个size_t值,它与unsigned int完全不同,尽管在大多数实现中size_t可以是unsigned int的别名。 但保持差异很重要。


注意:如果字符串存储在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