[英]Concatenate 3 strings and return a pointer to the new string C
我想知道是否有人可以幫助我,我正在嘗試連接 3 個字符串並返回一個指向新字符串的指針。 我似乎無法弄清楚如何使用 strncat 而不是 strcat 和 strncpy 而不是 strcpy 來做到這一點。 我只學習 c,所以任何幫助都會。 不勝感激。
char *
concatenate(char *a, char *b, char *d)
{
char str[80];
strcpy (str, a);
strcat (str,b);
strcat (str,d);
puts (str);
return (NULL);
}
您不能這樣做,您將返回一個指向本地數組的指針,該指針在函數返回后不再有效,此外,您不檢查緩沖區溢出。
這是分配內存的快速而骯臟的版本:
#include <stdlib.h>
#include <string.h>
char *concatenate(const char *a, const char *b, const char *c) {
return strcat(strcat(strcpy(malloc(strlen(a) + strlen(b) + strlen(c) + 1,
a), b), c);
}
這是一個使用memcpy
並測試malloc
失敗的更詳細的版本:
#include <stdlib.h>
#include <string.h>
char *concatenate(const char *a, const char *b, const char *c) {
size_t alen = strlen(a);
size_t blen = strlen(b);
size_t clen = strlen(c);
char *res = malloc(alen + blen + clen + 1);
if (res) {
memcpy(res, a, alen);
memcpy(res + alen, b, blen);
memcpy(res + alen + blen, c, clen + 1);
}
return res;
}
它應該更有效,因為它不執行strcpy
和strcat
所做的額外掃描,但只有仔細的基准測試才能證明它是否是對上述簡單版本的真正改進。
如果您需要將 3 個字符串連接到現有緩沖區中,一個非常簡單的解決方案是:
char dest[DEST_SIZE];
snprintf(dest, sizeof dest, "%s%s%s", a, b, c);
你的 str 對你的函數來說是本地的。
您可以向連接的字符串中添加第四個參數,也可以在函數內部對其進行 malloc,只需確保在使用后將其釋放即可。
char *concatenate(char *a, char *b, char *c)
{
int size = strlen(a) + strlen(b) + strlen(c) + 1;
char *str = malloc(size);
strcpy (str, a);
strcat (str, b);
strcat (str, c);
return str;
}
int main(void) {
char *str = concatenate("bla", "ble", "bli");
printf("%s", str);
free(str);
return 0;
}
也許是這樣的:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * concatenate(const char *a, const char *b, const char *d)
{
/* calculate the length of the new string */
size_t len = strlen(a) + strlen(b) + strlen(d);
/* allocate memory for the new string */
char* str = malloc(len + 1);
/* concatenate */
strcpy(str, a);
strcat(str, b);
strcat(str, d);
/* return the pointer to the new string
* NOTE: clients are responsible for releasing the allocated memory
*/
return str;
}
int main(void)
{
const char a[] = "lorem";
const char b[] = "impsum";
const char d[] = "dolor";
char* str = concatenate(a, b, d);
printf("%s\n", str);
free(str);
return 0;
}
如果您想要更通用的東西(例如連接 N 個字符串),您可以在此處查看 glib 庫的 g_strconcat 的實現:https ://github.com/GNOME/glib/blob/master/glib/gstrfuncs。 c#L563
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.