[英]Is there a standard C function for computing the string length up to some limit?
考虑一种情况:我有一个已知长度的缓冲区,可能存储一个以null结尾的字符串,我需要知道字符串的长度。
问题是如果我使用strlen()
并且字符串结果不是以null结尾,则程序在读取超出缓冲区结束时会运行到未定义的行为。 所以我想要一个像下面这样的函数:
size_t strlenUpTo( char* buffer, size_t limit )
{
size_t count = 0;
while( count < limit && *buffer != 0 ) {
count++;
buffer++;
}
return count;
}
所以它返回字符串的长度,但从不尝试读取超出缓冲区的结束。
C库中是否已有这样的功能,还是我必须使用自己的功能?
使用memchr(string, 0, limit)
,如:
size_t strlenUpTo(char *s, size_t n)
{
char *z = memchr(s, 0, n);
return z ? z-s : n;
}
根据我的文档,POSIX有size_t strnlen(const char *src, size_t maxlen);
n = strnlen("foobar", 7); // n = 6;
n = strnlen("foobar", 6); // n = 6;
n = strnlen("foobar", 5); // n = 5;
你可以使用strnlen
。 这是它的手册页:
NAME
strnlen - determine the length of a fixed-size string
SYNOPSIS
#include <string.h>
size_t strnlen(const char *s, size_t maxlen);
DESCRIPTION
The strnlen function returns the number of characters in
the string pointed to by s, not including the terminating
'\0' character, but at most maxlen. In doing this, strnlen
looks only at the first maxlen characters at s and never
beyond s+maxlen.
RETURN VALUE
The strnlen function returns strlen(s), if that is less
than maxlen, or maxlen if there is no '\0' character among
the first maxlen characters pointed to by s.
CONFORMING TO
This function is a GNU extension.
SEE ALSO
strlen(3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.