开始字符串相关操作前前先明确一下几个细节知识点:
1:可以用数组表达方式表示字符串
char *str="hello world";
printf("%c\n",str[4]);//输出o
2:下面这个会系统崩溃,因为字符串存储在文字常量区,不能改变
char*str="hello world";
str[4]=str[2];//错误,字符串存储在文字常量区,不能改变
printf("%c\n",str[4]);
3:数组和字符串转换时,虽然编译器会自动转换,但是加强制转换符转换,运行速度更快。如下例子,正确
int s=(int)'a';//int s=’a’;这种写法正确
charb=(char)s;
printf("%c\n",b);//输出a
4:int ar[]={1,2,3};数组长度为3
5:数组与指针
int a[][3]={1,2,3,4,5,6,7,8,9};
int(*p)[3]=a;
printf("%d\n",*(*p+1));//输出:2
printf("%d\n",*(*(p+1)+1));//输出:5
printf("%d\n",*(*(p+2)+2));//输出:9
地址
p | *p | *p+1 | *p+2 |
1 | 2 | 3 | |
P+1 | *(p+1) | *(p+1)+1 | *(p+1)+2 |
4 | 5 | 6 | |
P+2 | *(p+2) | *(p+2)+1 | *(p+2)+2 |
7 | 8 | 9 |
//
int a[3]={1,2,3};
intb[3]={4,5,6};
int *p[3];
*p=a;//将a数组地址赋给p[0],
*(p+1)=b;//等价p[1]=b;
printf("%d\n",*(*p+1));//输出:2
printf("%d\n",*(*(p+1)+1));//输出:5
//p[3]数组元素都是指针
数组元素 *p 或p[0] | 地址*p | *p+1 | *p+2 |
1 | 2 | 3 | |
*(p+1) 或p[1] | *(p+1) | *(p+1)+1 | *(p+1)+2 |
4 | 5 | 6 |
1:反转字符数组
#include<stdio.h>
char *string_reverse(char *str);
int main()
{
charstr[]="hello world";
//如果char *str=”hello world”程序会崩溃,因为字符串常量
string_reverse(str);
printf("%s\n",str);
return 0;
}
char *string_reverse(char *s)
{
char* h =s; /* h指向s的头部 */
char* t =s; /* t指向s的尾部 */
charch;
while(*t++!='\0')
{};
t--; /* 与t++抵消 */
t--; /* 回跳过结束符'\0',t指向最后一个字符 */
/* 当h和t未重合时,交换它们所指向的字符 */
while(h <t)
{
ch =*h;
*h =*t; /* h向尾部移动 */
*t=ch; /* t向头部移动 */
h++;
t--;
}
return(s);
}