我有一個字符數組:串連字符數組用C
char* name = "hello";
我要添加一個擴展,這個名字使它
hello.txt
我怎樣才能做到這一點?
name += ".txt"
將無法正常工作
我有一個字符數組:串連字符數組用C
char* name = "hello";
我要添加一個擴展,這個名字使它
hello.txt
我怎樣才能做到這一點?
name += ".txt"
將無法正常工作
看一看在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 */
#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
}
我有一個字符數組:
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 Strings的C FAQ的可能的幫助。問題6.5和8.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;
}
asprintf
不是100%的標準,但它通過GNU和BSD標準C庫是可用的,所以你可能有它。它分配輸出,所以你不必坐在那裏數字字符。
char *hi="Hello";
char *ext = ".txt";
char *cat;
asprintf(&cat, "%s%s", hi, ext);
不要忘記釋放name_with_extension! – 2010-02-07 21:04:09
謝謝,這個很好用 – user69514 2010-02-07 22:02:34
你可以寫'const char * name,* extension'嗎?字符串文字*不是* char *'。 – ephemient 2010-02-07 22:03:09