首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >strcat的反转

strcat的反转
EN

Stack Overflow用户
提问于 2009-11-04 15:04:02
回答 2查看 6.2K关注 0票数 0

我知道strcat(dest, src)src附加到dest,并返回dest。现在,如果我想将dest附加到src -即在dest中的dest之前插入字符串src -有什么方法可以做到吗?

我尝试使用strcat,类似于

代码语言:javascript
复制
dest = strcat(dest, src);

但不能让它工作。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-11-04 16:46:42

下面是一个经过简单测试的strlprecat()实现,它或多或少遵循了OpenBSD的'strlxxx()‘函数风格:

  • 传递目标缓冲区的长度,
  • 始终终止结果字符串(如果缓冲区大小大于0),
  • 返回所需的缓冲区长度(不包括终止符)

因此,此函数永远不会导致缓冲区溢出,但可能会导致字符串被截断(因此会破坏缓冲区中的原始字符串)。

无论如何,我发现一个类似的函数偶尔也很有用:

代码语言:javascript
复制
size_t
strlprecat( char* dst, const char * src, size_t size)
{
    size_t dstlen = strnlen( dst, size);
    size_t srclen = strlen( src);
    size_t srcChars = srclen;
    size_t dstChars = dstlen;

    if (0 == size) {
        /* we can't write anything into the dst buffer */
        /*  -- bail out                                */

        return( srclen + dstlen);
    }

    /* determine how much space we need to add to front of dst */

    if (srcChars >= size) {
        /* we can't even fit all of src into dst */
         srcChars = size - 1;
    }

    /* now figure out how many of dst's characters will fit in the remaining buffer */
    if ((srcChars + dstChars) >= size) {
        dstChars = size - srcChars - 1;
    }

    /* move dst to new location, truncating if necessary */
    memmove( dst+srcChars, dst, dstChars);

    /* copy src into the spot we just made for it */
    memcpy( dst, src, srcChars);

    /* make sure the whole thing is terminated properly */
    dst[srcChars + dstChars] = '\0';

    return( srclen + dstlen);
}

可以随意修改它,这样它就不会处理缓冲区长度(盲目地将内容移动到所需的位置),或者在缓冲区不够大的情况下只返回错误而不做任何操作。

哦,当然,如果你修复了任何bug,也可以发表评论。

票数 4
EN

Stack Overflow用户

发布于 2009-11-04 15:07:11

如果您希望在不修改src的情况下完成此操作,则可以分两步完成:

代码语言:javascript
复制
strcpy(temp, src);
strcat(temp, dest);

为了清楚起见,省略了所有错误处理和确定足够大的temp大小。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1672112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档