字符串插入以及字符串结束标志的考察
问题描述:
判断字符ch是否与str所指字符串中的某个字符相同;若相同则什么也不做,若不同,则将其插入到字符串的最后。
样例输入:
abcde
f
样例输出:
abcdef
关于这个程序代码,刚开始不是很理解,向老师学习断点调试后才恍然大悟。
断点调试截图:
源码如下:
#include<stdlib.h> #include<conio.h> #include<stdio.h> #include<string.h> void fun (char *str,char ch) { while(*str &&*str!= ch) //字符ch是否与str所指字符串中的某个字符不同时什么也不做 str++; //指针移动到下一个字符 if(*str=='\0') //当指针指向字符串结束处时执行下列代码 { str[0]=ch; //将现在指针指向的位置处的值'\0'替换成ch变量中表示的字符 str[1]='\0'; //指针的下一个位置重新赋值为字符串结束标志'\0'。 } } void main() { char s[81],c; system("cls"); //清屏函数,所用头文件#include<stdlib.h> printf("\n Please enter a string:"); gets(s); //键盘接受一个字符串 printf("\n Please enter the character to search:"); c=getchar(); fun(s,c); //函数调用,传递地址,其值会改变。 printf("\n The result is %s \n",s); }
程序截图:
*********************
交流即分享,分享才能进步!
不对之处,还请各位前辈多多指教。
by 星云
********************