C语言逆序字符串数组
程序员文章站
2022-06-22 12:05:55
问题描述:有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student".
代码实现:
&nbs...
问题描述:有一个字符数组的内容为:"student a am i",请你将数组的内容改为"i am a student".
代码实现:
#include <stdio.h> void swap(char *a,char *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } void reverse(char *arr,int left,int right)//student a am i { while(left < right) { swap(&arr[left],&arr[right]);//arr[0] left++; right--; } } int main() { int left = 0; int right = 0; char arr[]="student a am i"; reverse(arr,0,sizeof(arr)/sizeof(arr[0])-2);//student\0 while(arr[right] != '\0') { while(arr[right] != '\0'&&arr[right] != ' ') { right++; } right--; reverse(arr,left,right); left = right+2; right = left; } printf("%s\n",arr); return 0; }
结果是: