反转字符串(数组和指针两种方式)

问题:

1.反转字符串,比如str=“hello world!!!",反转后ret=“!!!dlrow olleh";

数组方式代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char* reverse(char inp[],int size){
        assert(inp != NULL && size>=0); //NULL代表空地址,null只是一个符号
        int i=0,j=size-1;
        while(i<j){
          char tmp=inp[i];
          inp[i]=inp[j];
          inp[j]=tmp;
          i++;j--;
        }
        return inp;
}

int main(){
  char input[]={'h','e','l','l','o','!','!','\0'};
  char* ret = reverse(input,7);
  printf("%s\n",ret);
  return 0;
}

输出:

[root@admin Desktop]# ./a.out
!!olleh
[root@admin Desktop]#

 

指针方式代码如下

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char* reverse(char* inp)
{
  assert(inp != NULL);
  char* p=inp;
  char* q=inp;
  while(*q != '\0') q++;
  q-=1;
  while(p<q)
  {
    printf("    p = %c; q = %c\n ",*p,*q);
    char tmp = *p;
    *p = *q;
    *q = tmp;
    p++;
    q--;
  }
  return inp;
}

int main(){
  char input[] = {'h','e','l','l','o',' ','b','a','b','y','!','!','\0'};
  char* ret = reverse(input);
  printf("result = %s\n",ret);
  return 0;
}

 

 

[root@admin Desktop]# ./a.out
    p = h; q = !
     p = e; q = !
     p = l; q = y
     p = l; q = b
     p = o; q = a
     p =  ; q = b
 result = !!ybab olleh
[root@admin Desktop]#

 

转载于:https://www.cnblogs.com/McQueen1987/p/3920549.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值