1 C字符串删除特定字符,实际上利用了函数重新修改了特定地址上的字符串,而且是按照添加的方式修改的!
void
del_chr(
char
*s,
char
ch )
{
char
*t=s;
//目标指针先指向原串头
while
( *s !=
'\0'
)
//遍历字符串s
{
if
( *s != ch )
//如果当前字符不是要删除的,则保存到目标串中
*t++=*s;
s++ ;
//检查下一个字符
}
*t=
'\0'
;
//置目标串结束符。
}
void
main()
{
char
str[]=
"***abcde***fghi***"
;
del_chr(str,
'*'
);
printf
(
"str=【%s】\n"
, str );
}
方法二
在一个函数里面实现,但是要new char新开辟一块地址;
int main()
{
char str[] = "we are stu!";
char *zcl = new char;
char *cxl = zcl;
int len = strlen(str);
for (int i = 0; i < len; i++)
{
if (str[i] == 'w' || str[i] == 'e')
{
zcl = zcl;
}
else
{
*zcl = str[i];
zcl++;
}
}
*zcl = '\0';
cout << cxl << endl;
system("pause");
return 0;
}
方法三,沿用之前地址上的字符串,但是不能再跟方法二一样用for循环了,因为循环的index已经发生了改变!
int main()
{
char str[] = "we are stu!";
char *zcl = str;
char *cxl = zcl;
int len = strlen(str);
int i = 0;
while (str[i]!='\0')
{
if (str[i] == 'w' || str[i] == 'e')
{
zcl = zcl;
i++;
}
else
{
*zcl = str[i];
zcl++;
i++;
}
}
*zcl = '\0';
cout << cxl << endl;
system("pause");
return 0;
}