将字符插入字符串 [英] Inserting characters into a string

查看:53
本文介绍了将字符插入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 "" 添加到 {"status":true} 以便字符串看起来像 "{"status":"true"}".如何在特定位置向字符串插入字符?

I want to add "" to {"status":true} so that the string looks like "{"status":"true"}". How can I insert characters to a string at specific locations?

我尝试了 strncat(),但没有得到想要的结果.我读到您需要为此创建自己的函数.谁能给我举个例子?

I tried strncat(), but wasn't able to get the desired result. I read that you need to create your own function for that. Can anyone show me an example?

推荐答案

是的,您需要为此编写自己的函数.

Yes, you will need to write your own function for that.

请注意,C 中的字符串是 char[],即字符数组,并且具有固定大小.

Note that a string in C is a char[], i.e. an array of characters, and is of fixed size.

您可以做的是,创建一个作为结果的新字符串,将主题字符串的第一部分复制到其中,附加中间的字符串,并附加主题字符串的后半部分.

What you can do is, create a new string that serves as the result, copy the first part of the subject string into it, append the string that goes in the middle, and append the second half of the subject string.

代码类似于,

// inserts into subject[] at position pos
void append(char subject[], const char insert[], int pos) {
    char buf[100] = {}; // 100 so that it's big enough. fill with zeros
    // or you could use malloc() to allocate sufficient space
    // e.g. char *buf = (char*)malloc(strlen(subject) + strlen(insert) + 2);
    // to fill with zeros: memset(buf, 0, 100);

    strncpy(buf, subject, pos); // copy at most first pos characters
    int len = strlen(buf);
    strcpy(buf+len, insert); // copy all of insert[] at the end
    len += strlen(insert);  // increase the length by length of insert[]
    strcpy(buf+len, subject+pos); // copy the rest

    strcpy(subject, buf);   // copy it back to subject
    // Note that subject[] must be big enough, or else segfault.
    // deallocate buf[] here, if used malloc()
    // e.g. free(buf);
}

此处的工作示例

这篇关于将字符插入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆