2010-02-07 44 views
27

我有一个字符数组:串连字符数组用C

char* name = "hello"; 

我要添加一个扩展,这个名字使它

hello.txt 

我怎样才能做到这一点?

name += ".txt"将无法​​正常工作

回答

44

看一看在strcat功能。

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

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 */ 
+18

不要忘记释放name_with_extension! – 2010-02-07 21:04:09

+0

谢谢,这个很好用 – user69514 2010-02-07 22:02:34

+2

你可以写'const char * name,* extension'吗?字符串文字*不是* char *'。 – ephemient 2010-02-07 22:03:09

8

首页复印当前字符串到一个更大的阵列strcpy,然后使用strcat

例如,你可以这样做:

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

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

你可以复制和粘贴在这里的答案,或者你可以去阅读我们的主机乔尔有什么看法strcat

+2

真的很好链接 – dubbeat 2012-05-29 13:19:07

1
#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 
} 
14

我有一个字符数组:

char* name = "hello"; 

没有,你有一个字符指针string literal。在许多用法中,您可以添加const修饰符,具体取决于您是否对名称指向的或字符串值“hello”更感兴趣。你不应该试图修改文字(“你好”),因为bad things can happen

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

我建议在C编程语言(第28页第二版)阅读字符数组,第1.9节。我强烈建议阅读这本小书(< 300页),以了解C.

而且你的问题,第6 - Arrays and Pointers和第8条 - Characters and StringsC FAQ的可能的帮助。问题6.58.4可能是开始的好地方。

我希望这可以帮助您理解您的摘录不起作用的原因。其他人已经概述了需要进行哪些更改才能使其发挥作用基本上你需要一个char数组(一个字符数组),它足够大以存储整个字符串,并带有终止(结束)的'\ 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; 
} 
4

asprintf不是100%的标准,但它通过GNU和BSD标准C库是可用的,所以你可能有它。它分配输出,所以你不必坐在那里数字字符。

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

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