#include <stdio.h>
#include <string.h>
void retStr(char* str);
int inversion(char *p,char *bufResult);
int trimSpace(char *inStr,char *outStr);
int main(int argc,char* argv[])
{
char str[] = " abc de fg ";
char outStr[1024];
memset(outStr,0,sizeof(outStr));
trimSpace(str,outStr);
printf("outstr:%s\n",str);
printf("outstr:%s\n",outStr);
// char str[] = "abcdefg";
// char buf[1024];
// memset(buf,0,sizeof buf);
//
// inversion(str,buf);
//
// printf("buf:%s\n",buf);
// retStr(str);
// printf("str:%s\n",str);
return 0;
}
//字符串翻转(1)
void retStr(char* str)
{
//必须要显示分配内存
int length = strlen(str);
char *p1 = str;
char *p2 = str + length - 1;
while(p1 < p2)
{
char temp = *p1;
*p1 = *p2;
*p2 = temp;
++p1;
--p2;
}
}
//通过递归的方式,逆向打印
//递归和全局变量(把逆序的结果存入全局变量)
//递归和非全局变量(递归指针做函数参数)
int inversion(char *p,char *bufResult)
{
if(p == NULL || bufResult == NULL || *p == '\0')//递归结束的异常条件,//递归结束的条件
return 0;
//递归两点:参数的入栈模型和函数的调用模型
inversion(p+1,bufResult);//此时没有执行打印 而是执行了函数调用(重点理解)
//让每一个字符的地址入栈
//printf("%c",*p);
strncat(bufResult,p,1);
return 0;
}
//通过循环求非空字符串
int trimSpace(char *inStr,char *outStr)
{
char *p = inStr;
int num = 0;
if (inStr == NULL || outStr == NULL)
{
num = -1;
printf("func trimSpace()check (inStr == NULL || outStr == NULL)error:%d\n",num);
}
while(*p++)
{
if(*p == ' ')
continue;
else
{
*outStr = *p;
outStr++;
}
}
return num;
}
字符串逆序翻转
最新推荐文章于 2020-11-08 08:35:37 发布