2 回答
TA贡献1845条经验 获得超8个赞
//顺序存储中替换
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;
}
}
}
}
- 2 回答
- 0 关注
- 653 浏览
相关问题推荐
添加回答
举报