是否有一种优雅的、行业标准的方法来实现C中的substr?

是否有一种优雅的、行业标准的方法来实现C中的substr?,c,string,substring,C,String,Substring,是否有一种优雅的、跨平台的、行业标准的方法在C中实现substr() 还是每个开发者都在重新发明轮子 编辑:添加了“跨平台”。类似于: #include <string.h> char* substr(int offset, int len, const char* input) { /* this one assumes that strlen(input) >= offset */ return strndup(input+offset, len); }

是否有一种优雅的、跨平台的、行业标准的方法在C中实现
substr()

还是每个开发者都在重新发明轮子

编辑:添加了“跨平台”。

类似于:

#include <string.h>
char* substr(int offset, int len, const char* input)
{
    /* this one assumes that strlen(input) >= offset */
    return strndup(input+offset, len);
}
#包括
字符*子字符(整数偏移量、整数长度、常量字符*输入)
{
/*这一个假设strlen(输入)>=offset*/
返回strndup(输入+偏移,len);
}
编辑:添加了偏移量>strlen的处理,并删除了strndup的用法

#include <string.h>
#include <stdlib.h>

char* substr(size_t offset, size_t len, const char* input)
{
    const size_t inputLength = strlen(input);
    if(offset <= inputLength)
    {
        size_t resultLength = inputLength-offset;
        char* result = NULL;
        if (len < resultLength)
        {
            resultLength = len;
        }
        result = malloc(resultLength+1);
        if(NULL != result)
        {
            strncpy(result, input+offset, resultLength);
            result[resultLength] = 0;
        }
        return result;
    }
    else
    {
        /* Offset is larger than the string length */
        return NULL;
    }
}
#包括
#包括
字符*子字符(大小偏移、大小长度、常量字符*输入)
{
常量大小\u t输入长度=strlen(输入);

尽管(offset我对原始问题的评论是这样的,但问题是这样一个函数需要一个缓冲区来存储结果,并且不清楚这是由调用方提供还是由函数实例化(留下了以后如何销毁它的问题),甚至通过修改原始字符串就地创建。在不同的情况下,您可能需要不同的行为,因此滚动自己的行为可能是有益的(在任何情况下都是微不足道的)


请注意,在上述所有情况下,参数的有效性(如边界检查和确定开始<结束)由调用方决定,在这方面,它们反映了标准字符串库的原理。在大多数情况下,我更喜欢第一个参数,因为它具有最大的实用性,并且更符合标准库的设计。MeMyVE()被用于MyCyPy.(),以便源和目的地可以是相同的位置,如果不需要,则使用MEMCYP()可能更有效。加里:是的。@鲁迪:您应该真正处理“代码>偏移量”(STRLIN(输入)< /代码> @ JeremyP:您认为什么是“跨平台”)??
strndup
是一个POSIX函数,不是ISO函数,因此不是通用的。即使使用POSIX,strndup()直到2006年才作为标准的一部分出现。为了便于移植,您的函数必须实现strndup()的功能。请参阅底部的注释,因此它跨越了大多数平台。唯一缺少的可能是Windows,它将非常容易实现。您最好在此处使用
memcpy()
而不是
strncpy()< /C++ >,因为您知道您复制的确切长度,而且您手动添加了NUL终结符。严格地说,除非定义函数<代码>子串(< /C>)的所需参数、结果和语义,否则问题毫无意义。您指定它的方式将决定其实现。(string,startindex,length)好的,在我的建议中我有startindex,endindex,但它们很容易更改;除非有人真的反对(或编辑它们),否则我会让它们保持不变。最后一个substr函数,源指针应该是char*类型,而不是const char*,因为您要修改字符串
// Caller supplied destination
char* substr( const char* source, size_t start, size_t end, char* dest )
{
    memmove( dest, &source[start], end - start ) ;
    dest[end - start] = 0 ;
    return dest ;
}

// Automatically instantiated destination (and a memory leak!)
char* substr( const char* source, size_t start, size_t end )
{
    char* dest = malloc( end - start + 1) ;
    memcpy( dest, &source[start], end - start ) ;
    dest[end - start] = 0 ;
    return dest ;
}

// Modify in-place (original string truncated)
char* substr( char* source, size_t start, size_t end )
{
    source[end+1] = 0 ;
    return &source[start] ;
}