C语言 C 字符串追加

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5901181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:34:35  来源:igfitidea点击:

C string append

cstring

提问by Udara S.S Liyanage

I want to append two strings. I used the following command:

我想附加两个字符串。我使用了以下命令:

new_str = strcat(str1, str2);

This command changes the value of str1. I want new_strto be the concatanation of str1and str2and at the same time str1is not to be changed.

此命令更改 的值str1。我想new_str成为str1str2同时str1不被改变的串联。

回答by Charlie Martin

You need to allocate new space as well. Consider this code fragment:

您还需要分配新空间。考虑这个代码片段:

char * new_str ;
if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
    new_str[0] = '
strcat(new_str,str1);
strcat(new_str,str2);
'; // ensures the memory is an empty string strcat(new_str,str1); strcat(new_str,str2); } else { fprintf(STDERR,"malloc failed!\n"); // exit? }

You might want to consider strnlen(3)which is slightly safer.

您可能需要考虑strnlen(3)哪个更安全。

Updated, see above. In some versions of the C runtime, the memory returned by mallocisn't initialized to 0. Setting the first byte of new_strto zero ensures that it looks like an empty string to strcat.

已更新,见上文。在 C 运行时的某些版本中,返回的内存malloc未初始化为 0。将 的第一个字节设置new_str为零可确保它看起来像 strcat 的空字符串。

回答by VirtualTroll

do the following:

请执行下列操作:

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

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");

    int i;
    for (i = 0; i < 10; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

回答by Joel Falcou

You'll have to strncpystr1into new_stringfirst then.

那么你必须先strncpystr1进入new_string

回答by Wei

I write a function support dynamic variable string append, like PHP str append: str + str + ... etc.

我写了一个支持动态变量字符串追加的函数,比如PHP str append: str + str + ... 等。

// open the stream
FILE *stream;
char *buf;
size_t len;
stream = open_memstream(&buf, &len);

// write what you want with fprintf() into the stream
fprintf(stream, "Hello");
fprintf(stream, " ");
fprintf(stream, "%s\n", "world");

// close the stream, the buffer is allocated and the size is set !
fclose(stream);
printf ("the result is '%s' (%d characters)\n", buf, len);
free(buf);

回答by Christophe Quintard

Consider using the great but unknown open_memstream() function.

考虑使用伟大但未知的 open_memstream() 函数。

FILE *open_memstream(char **ptr, size_t *sizeloc);

FILE *open_memstream(char **ptr, size_t *sizeloc);

Example of usage :

用法示例:

strcpy(str1+strlen(str1), str2);

If you don't know in advance the length of what you want to append, this is convenient and safer than managing buffers yourself.

如果您事先不知道要追加的内容的长度,这比自己管理缓冲区方便且安全。

回答by Barun Parichha

char *new_str;
asprintf(&new_str,"%s%s",str1,str2);

回答by frmdstryr

You could use asprintfto concatenate both into a new string:

您可以使用asprintf将两者连接成一个新字符串:

char gStrSshCommand[SSH_COMMAND_MAX_LEN]; // declare ssh command string

strcpy(gStrSshCommand, ""); // empty string

void appendSshCommand(const char *substring) // append substring
{
  sprintf(gStrSshCommand, "%s %s", gStrSshCommand, substring);
}

回答by Zac

I needed to append substrings to create an ssh command, I solved with sprintf(Visual Studio 2013)

我需要附加子字符串来创建一个 ssh 命令,我用sprintf(Visual Studio 2013)解决了

char * my_strcat(const char * str1, const char * str2)
{
   char * ret = malloc(strlen(str1)+strlen(str2));

   if(ret!=NULL)
   {
     sprintf(ret, "%s%s", str1, str2);
     return ret;
   }
   return NULL;    
}

回答by maheshgupta024

man page of strcat says that arg1 and arg2 are appended to arg1.. and returns the pointer of s1. If you dont want disturb str1,str2 then you have write your own function.

strcat 的手册页说 arg1 和 arg2 附加到 arg1.. 并返回 s1 的指针。如果您不想打扰 str1,str2,那么您可以编写自己的函数。

strncpy(new_str, str1, strlen(str1));
strcat(new_str, str2);

Hope this solves your purpose

希望这能解决你的目的

回答by Sitnik

You can try something like this:

你可以尝试这样的事情:

##代码##

More info on strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

有关 strncpy 的更多信息:http://www.cplusplus.com/reference/clibrary/cstring/strncpy/