6-26 D字符串的連接函數 (5分)


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;
 
  
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM