C语言 字符串操作两头堵模型
2016-03-22 11:03
645 查看
//字符串操作两头堵模型练习 #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"); }
相关文章推荐
- MFC UpdateData
- [转]C语言单引号和双引号的区别
- 简单的毫秒级C语言耗时打印宏
- 基于c++11设计一个定时器timer
- C++ Primer 5th - 1.3 关于注释
- C语言的宏定义(1)—— #if defined和#if !defined
- VS2005 vc++ 后缀文件解释
- C语言变量声明加冒号的用法(占位符)
- 【小镇的技术天梯】从头开始写算法,C语言hash表
- C++ 内存模型——虚表(vtbl)的访问
- C++ 对象模型(二)
- c++四种分配内存的方法整理
- C++中overload,override,overwrite的区别
- c++编程拾贝(二)
- C++中的值传递 | 指针传递 | 引用传递
- 八大排序之直接插入排序
- 冒泡排序
- 选择排序
- C++的四种cast操作符的区别--类型转换
- Lotto 迭代算法 cpp