字符串初始化
//1 指定长度
char buff[100] = {‘a’,‘b’,‘c’,‘d’};
//相当于字符串末尾有‘\0’,且‘\0’后面都会变成零
//1.2
char buff[2] = {‘a’,‘b’,‘c’,‘d’};
//如果初始化的个数大于内存的个数,编译错误。
//2.不指定长度
char buff[] = {‘a’,‘b’,‘c’,‘d’};
//buff是一个数组,不是一个以0结尾的字符串。
字符串反转
1.1
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
char buff[] = "abcdefg";
int len = strlen(buff);
char *p1 = buff;
char *p2 = buff +len - 1;
while(p1 < p2)
{
char temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
++p1;//向前
--p2;//向后
}
//因为我们没有改变'\0';所以不用加;
printf("buff:%s",buff);
}
1.2
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
int inverse(char *str)
{
int ret = 0;
if(str == NULL)
{
ret = -1;
printf("err int inverse(char *str)\n");
return ret;
}
char *buff = str;
int len = strlen(buff);
char *p1 = buff;
char *p2 = buff +len - 1;
while(p1 < p2)
{
char temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
++p1;//向前
--p2;//向后
}
//因为我们没有改变'\0';所以不用加;
return ret;
}
int main()
{
int ret = 0;
char buff[] = "abcdefg";
ret = inverse(buff);
printf("buff:%s",buff);
return ret;
}
2.1通过递归方式,逆向打印
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
//通过递归方式,逆向打印
int inverse(char *p)
{
if(p == NULL)//递归结束的异常条件
{
return 0;
}
if(*p == '\0')//递归结束条件
{
return 0;
}
inverse(p+1);//此时没有打印,而是让后面的入栈
printf("%c",*p);
return 0;
}
int main()
{
char buf[] = "abcdefg";
inverse(buf);
}
2.2//通过递归方式,逆向打印
//递归和全局变量(把逆序的结果存入全局变量)
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
char g_buf[1000];
//通过递归方式,逆向打印
//递归和全局变量(把逆序的结果存入全局变量)
int inverse(char *p)
{
if(p == NULL)
return 0;
if(*p =='\0')
return 0;
inverse(p+1);
//printf("%c",*p);
strncat(g_buf,p,1);//连接函数,不会覆盖
//strncpy(g_buf,p,1);//每次拷贝都在首地址
return 0;
}
int main()
{
char buf[] = "abcdefg";
memset(g_buf,0,sizeof(g_buf));
inverse(buf);
printf("%s:",g_buf);
}
2.3//通过递归方式,逆向打印
//递归和局部变量(把逆序的结果存入局部变量)
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
int inverse(char *from,char *to)
{
int ret = 0;
if(from == NULL||to ==NULL)
{
ret = -1;
printf("err inverse\n");
return ret;
}
char *buf = from;
char *c = to;
if(*buf == '\0')
{
*c = '\0';
return ret;
}
inverse(buf+1,c);
strncat(c,buf,1);
return ret;
}
int main()
{
int ret = 0;
char buf[] = "abcdefg";
char c[100];
ret = inverse(buf,c);
printf("c字符数组:%s",c);
return ret;
}