C语言 在 C 中连接字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2218290/
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 04:24:45  来源:igfitidea点击:

concatenate char array in C

cstringarrays

提问by user69514

I have a a char array:

我有一个字符数组:

char* name = "hello";

I want to add an extension to that name to make it

我想为该名称添加扩展名以使其成为

hello.txt

How can I do this?

我怎样才能做到这一点?

name += ".txt"won't work

name += ".txt"不会工作

回答by David Underhill

Have a look at the strcatfunction.

看看strcat函数。

In particular, you could try this:

特别是,你可以试试这个:

const char* name = "hello";
const char* extension = ".txt";

char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */

回答by mctylr

I have a char array:

char* name = "hello";

我有一个字符数组:

char* name = "hello";

No, you have a character pointer to a string literal. In many usages you could add the const modifier, depending on whether you are more interested in what namepoints to, or the string value, "hello". You shouldn't attempt to modify the literal ("hello"), because bad things can happen.

不,您有一个指向字符串文字的字符指针。在许多用法中,您可以添加 const 修饰符,这取决于您是对名称指向的内容更感兴趣,还是对字符串值“ hello”更感兴趣。您不应该尝试修改文字(“hello”),因为可能会发生不好的事情

The major thing to convey is that C does not have a proper (or first-class) string type. "Strings" are typically arrays of chars (characters) with a terminating null ('\0' or decimal 0) character to signify end of a string, or pointers to arrays of characters.

要传达的主要内容是 C 没有正确的(或一流的)字符串类型。“字符串”通常是字符(字符)数组,带有终止的空('\0' 或十进制 0)字符以表示字符串的结尾,或指向字符数组的指针。

I would suggest reading Character Arrays, section 1.9 in The C Programming Language(page 28 second edition). I strongly recommend reading this small book ( <300 pages), in order to learn C.

我建议阅读字符数组C 编程语言(第 28 页第二版)中第 1.9 节。我强烈推荐阅读这本小书(<300 页),以便学习 C。

Further to your question, sections 6 - Arrays and Pointersand section 8 - Characters and Stringsof the C FAQmight help. Question 6.5, and 8.4might be good places to start.

另外你的问题,第6 -数组和指针和第8条-字符和字符串Ç常见问题可能会有帮助。问题6.58.4可能是开始的好地方。

I hope that helps you to understand why your excerpt doesn't work. Others have outlined what changes are needed to make it work. Basically you need an char array (an array of characters) big enough to store the entire string with a terminating (ending) '\0' character. Then you can use the standard C library function strcpy (or better yet strncpy) to copy the "Hello" into it, and then you want to concatenate using the standard C library strcat (or better yet strncat) function. You will want to include the string.h header file to declare the functions declarations.

我希望这能帮助您理解为什么您的摘录不起作用。其他人概述了需要进行哪些更改才能使其发挥作用。基本上,您需要一个足够大的字符数组(字符数组)来存储带有终止(结束)'\0' 字符的整个字符串。然后,您可以使用标准 C 库函数 strcpy(或更好的 strncpy)将“Hello”复制到其中,然后您想使用标准的 C 库 strcat(或更好的 strncat)函数进行连接。您需要包含 string.h 头文件来声明函数声明。

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

int main( int argc, char *argv[] )
{
    char filename[128];
    char* name = "hello";
    char* extension = ".txt";

    if (sizeof(filename) < strlen(name) + 1 ) { /* +1 is for null character */
        fprintf(stderr, "Name '%s' is too long\n", name);
        return EXIT_FAILURE;
    }
    strncpy(filename, name, sizeof(filename));

    if (sizeof(filename) < (strlen(filename) + strlen(extension) + 1) ) {
        fprintf(stderr, "Final size of filename is too long!\n");
        return EXIT_FAILURE;
    }
    strncat(filename, extension, (sizeof(filename) - strlen(filename)) );
    printf("Filename is %s\n", filename);

    return EXIT_SUCCESS;
}

回答by Salv0

First copy the current string to a larger array with strcpy, then use strcat.

首先使用strcpy将当前字符串复制到更大的数组,然后使用strcat

For example you can do:

例如你可以这样做:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

回答by bk.

asprintfis not 100% standard, but it's available via the GNU and BSD standard C libraries, so you probably have it. It allocates the output, so you don't have to sit there and count characters.

asprintf不是 100% 标准,但它可以通过 GNU 和 BSD 标准 C 库获得,因此您可能已经拥有它。它分配输出,因此您不必坐在那里计算字符。

char *hi="Hello";
char *ext = ".txt";
char *cat;

asprintf(&cat, "%s%s", hi, ext);

回答by Will

You could copy and paste an answer here, or you could go read what our host Joel has to say about strcat.

您可以在此处复制并粘贴答案,或者您可以阅读我们的主持人 Joel 对strcat 的评论

回答by DigitalRoss

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

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

回答by CASO Student

You can concatenate strings by using the sprintf() function. In your case, for example:

您可以使用 sprintf() 函数连接字符串。在您的情况下,例如:

char file[80];
sprintf(file,"%s%s",name,extension);

And you'll end having the concatenated string in "file".

您将在“文件”中结束连接字符串。