字符串之反转

开始字符串相关操作前前先明确一下几个细节知识点:


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);                                                                                    

}

 

 

 

 

 

 

 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值