6-26 D字符串的連接函數 (5分)
D字符串是動態分配內存的字符串,它也采用char
數組來保存字符串中的字符,但是這個數組是在堆中動態分配得到的。
本題要求編寫D字符串的連接函數。
函數接口定義:
char *dstr_add(char *s, char c); char *dstr_concat(char *this, const char *that);
dstr_add
在s的后面加上一個字符c,返回新的字符串。 dstr_concat
在this后面加上字符串that,返回新的字符串。 這兩個函數的第一個參數都必須是D字符串,不能是靜態數組。
裁判測試程序樣例:
#include <stdio.h> #include <stdlib.h> #include <string.h> // 這兩個函數由系統提供 char *dstr_readword(); char *dstr_create(const char *s); char *dstr_add(char *s, char c); char *dstr_concat(char *this, const char *that); int main() { char *s = dstr_create("hello"); s = dstr_add(s, '!'); printf("%lu-%s\n", strlen(s), s); char *t = dstr_readword(); s = dstr_concat(s, t); free(t); printf("%lu-%s\n", strlen(s), s); free(s); } /* 請在這里填寫答案 */
輸入樣例:
123A
輸出樣例:
6-hello!
10-hello!123A
char *dstr_add(char *s, char c)
{
int str=strlen(s);
s=realloc(s,str*sizeof(char)+2) ;
s[str]=c;
s[str+1]='\0';
return s;
}
char *dstr_concat(char *this, const char *that)
{
int str_this=strlen(this);
int str_that=strlen(that);
this=realloc(this,(str_this+str_that+1)*sizeof(char));
strcat(this,that);
return this;
}