c - 是否有任何函数可以将字符作为字符串前缀并存储在同一个字符串中?

标签 c concatenation operators c-strings string-concatenation

我们如何在c中进行以下操作? s=“#”+s; 其中 s 是一个字符串。

我尝试过使用 strncat() 但连接后答案应存储在带有前缀“#”的 s 中。

最佳答案

假设s有足够的元素,可以通过以下方式为s添加一个字符的前缀:

  1. 通过 memmove() 将现有字符串滑动一(您不能使用 strcpy()memcpy(),因为它们不支持复制到重叠区域)
  2. 写入要添加到 s 第一个元素的字符。
#include <stdio.h>
#include <string.h>

int add_prefix(char* str, char c, size_t bufsz) {
    size_t strsize = strlen(str) + 1;

    if (bufsz <= strsize) {
        return -1;
    }

    memmove(str + 1, str, strsize); /* +1 for terminating null-character */
    str[0] = c;
    return 0;
}

int main(void) {
    char s[128] = "hello";

    printf("before add_prefix() : %s\n", s);

    add_prefix(s, '#', sizeof(s));
    printf("after  add_prefix() : %s\n", s);

    return 0;
}

关于c - 是否有任何函数可以将字符作为字符串前缀并存储在同一个字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67366890/

相关文章:

c - 释放分配的内存会导致程序卡在 Visual Studio 中,但不会卡在 CodeBlocks 中

c - #include 其他 C 程序

string - 在 Scala 中高效地重复字符/字符串 n 次

c - C : how this function works? 中的按位运算符

delphi - 如何将多个不同的记录(由于delphi限制而不是类)传递给一个函数?

c++ - 运算符重载的基本规则和惯用法是什么?

c - 查找 C 函数中的错误

c++ - 从 c/c++ 独立应用程序中的 zip 文件导入 python 包

ms-access - 在 MS Access 中将多行连接成一行

mysql - 使用双重连接选择多个表值