地下城天启者刷图加点:C语言问题求解

来源:百度文库 编辑:高考问答 时间:2024/04/28 22:12:15
删除在字符串中的一个字符函数如下:
#include<stdio.h>
#define N 80
void del_char(char *p,char x)
{
int i=0;
char *q=p;
for(;*p!='\0';p++)
if (*p!=x) *q++=*p;//这里该如何理解啊
*q='\0';
}
void main()
{
char c[N],*pt=c,x;
printf("enter a string:");
gets(pt);
printf("enter the char deleted:");
x=getchar();
del_char (pt,x);
printf("The new string is :%s\n",c);
}
运行效果如下:
enter a string:tool
enter the char deleted:o
The new string is :tl

*q++=*p
把p指向的字符赋值给q指向的字符(空间)然后q指向下一字符空间

去亲自运行一下就知道了
这里用指针进行字符串的操作,可以说正是C的优势
比如运行时:
Enter a string :hao hao xue xi
Enter the char deleted:h
The new string is :ao ao xue xi
此处不是删除了一个字符,而是删除了"这个"字符

for循环的作用就是把旧串p拷到新串q,条件是字符不等于'x'
子函数del_char()的变量定义中,i没用到,q完全可以这样定义:
char *q=NULL

这个del_char()写得不错,时间复杂度O(n),空间复杂度0,要我写,可能会写成O(n^2)的了。

if (*p!=x) *q++=*p;//这里该如何理解啊
:翻译:,如果指向P的指针不为X。那么就把P的指针地址给Q指针的下一个地址

不错,算法非常巧妙

当此时p指针的值于x不同,则把此时p的值赋值给q,指针q再指向后一位.再进入循环.

不知