這個問題在這里已經有了答案: 將字符附加到C中的字串? (12 個回答) 如何在C中將char連接到char *? (3 個回答) 如何在 C 中連接 const/literal 字串? (17 個回答) 5 小時前關閉。
我在 C 中有兩個字串。
char* lexeme = "this is an example";
char c = 'a';
我想將這兩個字串連接起來,結果是:
"this is an examplea"
我已經嘗試過使用 strcpy 和 strcat,但它給出了一個錯誤,因為第二個字符不是 char* 型別
uj5u.com熱心網友回復:
問題 1:lexeme是指向只讀記憶體的指標,因此您無法在該位置存盤或更改任何內容。
問題2:c不是字串而是單個字符。
您可以通過以下方式解決它:
- 查找 的字串長度
lexeme并將其存盤在變數old_length中。 - 分配 string 的“足夠大”副本
lexeme,例如使用mallocstrcpy。“足夠大”意味著原始字串的空間、一個附加字符以及最后的空終止符。 - 在新分配的字串(讓我們稱之為
newstr)中,將字符寫入 indexnewstr[old_length]。這是空終止符當前所在的位置,因此將被覆寫。 - 在新分配的字串中,將空終止符寫入 index
newstr[old_length 1]。
uj5u.com熱心網友回復:
您可以撰寫自己的例程來執行此操作:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *appended(char const* src, char const ch) {
size_t const size = strlen(src);
char* copy = malloc(size 2);
if (!copy) {
return 0;
}
memcpy(copy, src, size);
copy[size] = ch;
copy[size 1] = 0;
return copy;
}
int main() {
char* str = appended("Hello Worl", 'd');
if (!str) {
return EXIT_FAILURE;
}
puts(str);
free(str);
return EXIT_SUCCESS;
}
uj5u.com熱心網友回復:
我更喜歡上面的代碼。但我很快就寫了一些東西。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char lexeme[] = "this is an example";
char c = 'a';
int len_of_lexeme = strlen(lexeme);
char *concat_str = malloc(len_of_lexeme 2);
strcpy(concat_str, lexeme);
concat_str[len_of_lexeme] = c;
concat_str[len_of_lexeme 1] = '\0';
printf("concat_str = [%s]\n", concat_str);
free(concat_str);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/518354.html
標籤:C
