你好,在字符串中的replace(s,t1,t2)函数,求解释!

求两个函数,分别在顺序和链式存储方式下实现字符串的replace(s,t1,t2运算。(在字符串s中,用t2代替所有的t1.举例:若s=abcdef,t1=ab,t2=ww,则结果为wwcdef)。是数据结构的题目。
多谢了!!!

12345678_0001
浏览 654回答 2
2回答

精慕HU

//顺序存储中替换void myreplace(char *s,const char *t1,const char *t2){//顺序存储就是数组char *pwork = s;int p = 0;char *pleft = s,*pright = NULL;for ( p = 0 ; p < strlen(s) ; p++ ){if ( strncmp(pwork,t1,strlen(t1)) == 0 ){pright = pwork+strlen(t1);memset(pwork,0x0,strlen(t1));break;}pwork++;}strcpy(s,pleft);strcat(s,t2);strcat(s,pright);}//链式存储中替换struct cNode{char c;cNode *pNext;};//传入链表的头void myreplace(cNode *pHead,const char *t1,const char *t2){//首先将链表转换为字符串//定义一个临时的数组,要足够长,来转换链表为字符串char tmp[2048];cNode *pwork = pHead;int i;memset(tmp,0x0,sizeof(tmp));//循环是将链表转换为字符串for ( i = 0 ; i < 2048 ; i++ ){if ( pwork ){tmp[i] = pwork->c;pwork=pwork->pNext;}else{break;}}//调用上面替换字符串的方法替换myreplace(tmp,t1,t2);//重新恢复替换后的链表pwork = pHead;//循环是将字符串转换为链表for ( i = 0 ; i < strlen(tmp) ; i++ ){if ( pwork ){pwork->c = tmp[i];if ( pwork->pNext == NULL ){ //如果链表的长度不够容纳替换后的字符串//(通常发生在被替换字符串长度比用来替换的字符串长度短的情况下)//则生成新的结点pwork->pNext = (cNode *)malloc(sizeof(cNode));pwork->pNext->pNext = NULL;}else{pwork = pwork->pNext;}}}}
打开App,查看更多内容
随时随地看视频慕课网APP