//字符串操作两头堵模型练习 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> //去除字符串中的空格 //const char *pin的解释:const char *pin是用来限制指针pin指向的数据是个常量,不允许修改, //但是并不限制实参指针指向的数据也必须是一个常量 //这是为了防止传过来的参数pin所指向的数据不可以修改,但是却在函数里做了修改,导致程序报错,这是一种标准的写法 int removespace(const char *pin,char *pout){ int ERRO_MSG = 0; //验证传入参数是否为空 if (pin == NULL || pout==NULL) { ERRO_MSG = 1; printf("pin == NULL || pout==NULL erro msg key:%d\n", ERRO_MSG); return ERRO_MSG; } //两头堵模型就是要准备两个辅助指针,一个在头部,一个在尾部 int i = 0, j = 0; //定义不是空格的字符的个数 int index = 0; //不清楚具体循环次数,一般使用while或者do...while... //i从头开始 //注意:pin[i]==" "这么些是错误的," "是字符串(2个字符,'\0'也算一个),pin[1]是一个char类型 while (pin[i] != '\0'&&pin[i]==' '){ i++; } j = strlen(pin); //j从尾部开始 while (pin[j] != '\0'&&pin[i] ==' '){ j--; } index = j - i + 1; //例如 "ab" a的位置是0,b的位置是1,则1-0=1,实际字符个数是2 //拷贝字符串 strncpy(pout, pin + i, index); return ERRO_MSG; } void main(){ char buf2[] = " adfr "; //这里两种分配字符串的方式 //方式一(推荐) char buf[20] = { 0 }; //方式二(第二种方式,并没有初始化分配的内存,因此需要在函数中将p1指向的内存的数据初始化为'\0') char *p1 =(char *)malloc(sizeof(char)* 10); //初始化p1 memset(p1, 0, sizeof(p1)); //注意:memset()相比于char buf[20] = { 0 };这种方式要消耗更多的资源 removespace(buf2, buf); //malloc分配的内存必须回收 free(p1); printf("%s\n", buf); system("pause"); }
//字符串操作两头堵模型练习 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> //字符串反转 int reversestr(const char *pin,char *pout){//pin是形参,一个临时变量,pin的值发生变化,不会影响实参p的值 //定义返回key int ERRO_MSG = 0; //形参非空校验 if (pin == NULL || pout==NULL) { ERRO_MSG = 1; printf("pin == NULL || pout==NULL erro msg key:%d\n", ERRO_MSG); return ERRO_MSG; } //两头堵模型 int i = 0, j = strlen(pin)-1;//p[5]是'\0' while (j >= i){ //将字符一个个填入字符数组里 *pout++ = pin[j--]; } return ERRO_MSG; } void main(){ char *p = "abcde"; char strarr[10] = { 0 }; reversestr(p, strarr); printf("%s\n", strarr); system("pause"); }