将char字符串插入另一个char字符串

时间:2010-01-06 20:18:13

标签: c

好的,所以我有一个char stringA和char stringB,我希望能够在第x点将stringB插入stringA。

char *stringA = "abcdef";
char *stringB = "123";

产品为"ab123cdef"

有谁知道怎么做?提前致谢

5 个答案:

答案 0 :(得分:12)

char * strA = "Blahblahblah", * strB = "123", strC[50];
int x = 4;
strncpy(strC, strA, x);
strC[x] = '\0';
strcat(strC, strB);
strcat(strC, strA + x);
printf("%s\n", strC);

说明:

  1. 您声明要加入的两个字符串,以及您将要放入的第三个字符串。
  2. 您声明一个整数,告诉程序您希望将第二个字符串插入第一个字符串的字符数。
  3. strncpy函数将前x个字符复制到strC中。你必须在最后添加null('\ 0')字符,否则你可能会得到垃圾。
  4. Strcat复制第二个字符串。
  5. 另一个strcat,用于复制第一个字符串的剩余部分(strA + x)。
  6. 希望有所帮助。

    备注:记得使strC足够长以包含strA和strC,否则会产生分段错误。您可以通过将字符串声明为数组来完成此操作,就像在我的示例中一样。

答案 1 :(得分:8)

stringA和stringB都是指针 - 它们包含一块内存的起始地址。它们指向的内存包含连续的字符串:分别为“abcdef”和“123”。由于字符串是连续的块存储器(意味着给定字符的存储位置是前一个字节后的一个字节),因此在不先移动某些字符的情况下,不能在字符串的中间插入更多字符。在你的情况下你甚至不能真正做到这一点,因为为每个字符串分配的内存量足够大,足以容纳JUST字符串(忽略填充)。

您将要做的是将字符串复制到另一个内存块,一个为此目的分配的内存块,然后复制它们,以便第二个字符串在第一个字符串中开始x个字符。

其他几个SO用户已发布代码解决方案,但我认为您应该尝试自己找到确切的解决方案(希望我对正在发生的事情的高级解释会有所帮助)。

答案 2 :(得分:2)

int insert_pos = 5;
int product_length = strlen(stringA) + strlen(stringB) + 1;
char* product = (char*)malloc(product_length);
strncpy(product, stringA, insert_pos);
product[insert_pos] = '\0';
strcat(product, stringB);
strcat(product, stringA + insert_pos);
...
free(product);

答案 3 :(得分:1)

这是一个更通用的解决方案。

注意 destination必须在内存中有足够的空间来添加种子(例如,堆积大小超过strlen(seed)+strlen(destination)的堆分配数组)。所以,关于这个问题,你必须创建一个更大的数组。

/* 
    destination: a NULL terminated string
    pos: where insert seed
    seed: a NULL terminated string
*/
void insertString(char* destination, int pos, char* seed)
{
    char * strC;

    strC = (char*)malloc(strlen(destination)+strlen(seed)+1);
    strncpy(strC,destination,pos);
    strC[pos] = '\0';
    strcat(strC,seed);
    strcat(strC,destination+pos);
    strcpy(destination,strC);
    free(strC);
}

答案 4 :(得分:-1)

char *strInsert(char *str1, const char *str2, int pos) {
    size_t l1 = strlen(str1);
    size_t l2 = strlen(str2);

    if (pos <  0) pos = 0;
    if (pos > l1) pos = l1;

    char *p  = str1 + pos;
    memmove(p + l2, p, l1 - pos);
    memcpy (p, str2,  l2);
    return str1;
}