【问题标题】:Is there a standard C function for computing the string length up to some limit?是否有一个标准的 C 函数用于计算字符串长度达到某个限制?
【发布时间】:2010-12-14 10:48:43
【问题描述】:

考虑一种情况:我有一个已知长度的缓冲区,它可能存储一个以 null 结尾的字符串,我需要知道字符串的长度。

问题是如果我使用strlen() 并且字符串结果是不是空终止程序在读取缓冲区结束时遇到未定义的行为。所以我想要一个类似下面的函数:

 size_t strlenUpTo( char* buffer, size_t limit )
 {
     size_t count = 0;
     while( count < limit && *buffer != 0 ) {
        count++;
        buffer++;
     }
     return count;
 }

以便它返回字符串的长度,但从不尝试读取超出缓冲区的末尾。

C 库中是否已经有这样的功能,还是我必须使用自己的功能?

【问题讨论】:

    标签: c string


    【解决方案1】:

    使用memchr(string, 0, limit),如:

    size_t strlenUpTo(char *s, size_t n)
    {
        char *z = memchr(s, 0, n);
        return z ? z-s : n;
    }
    

    【讨论】:

      【解决方案2】:

      根据我的文档,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,您可以使用我的答案作为替代品。命名替换 strnlen 并确保它与 POSIX strnlen 函数具有相同的语义可能比制作一个名称不同且行为可能不同的版本更好。
      【解决方案3】:

      您可以使用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)
      

      【讨论】:

      • 注意符合部分。虽然它已经过时了; POSIX 2008 标准化了这个功能。但当然它仍然不是普通的 C。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2011-02-10
      • 2013-11-02
      • 2010-12-08
      • 2014-03-06
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多