2 回答

TA貢獻1845條經(jīng)驗 獲得超8個贊
//順序存儲中替換
void myreplace(char *s,const char *t1,const char *t2)
{
//順序存儲就是數(shù)組
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)
{
//首先將鏈表轉(zhuǎn)換為字符串
//定義一個臨時的數(shù)組,要足夠長,來轉(zhuǎn)換鏈表為字符串
char tmp[2048];
cNode *pwork = pHead;
int i;
memset(tmp,0x0,sizeof(tmp));
//循環(huán)是將鏈表轉(zhuǎn)換為字符串
for ( i = 0 ; i < 2048 ; i++ )
{
if ( pwork )
{
tmp[i] = pwork->c;
pwork=pwork->pNext;
}
else
{
break;
}
}
//調(diào)用上面替換字符串的方法替換
myreplace(tmp,t1,t2);
//重新恢復(fù)替換后的鏈表
pwork = pHead;
//循環(huán)是將字符串轉(zhuǎn)換為鏈表
for ( i = 0 ; i < strlen(tmp) ; i++ )
{
if ( pwork )
{
pwork->c = tmp[i];
if ( pwork->pNext == NULL )
{ //如果鏈表的長度不夠容納替換后的字符串
//(通常發(fā)生在被替換字符串長度比用來替換的字符串長度短的情況下)
//則生成新的結(jié)點
pwork->pNext = (cNode *)malloc(sizeof(cNode));
pwork->pNext->pNext = NULL;
}
else
{
pwork = pwork->pNext;
}
}
}
}
添加回答
舉報