C++ 字符串的倒置(reverse)

#include<iostream>
#include<cstdlib>
#include<cstring>
using namespace std;
void reverse(char *s,int n){
	int l=0;int r=n-1;
	while(l<r){
		char temp=s[l];
		s[l]=s[r];
		s[r]=temp;
		l++;
		r--;
	}
}
void print(char *s,int n){
	for(int i=0;i<n;i++){
		cout<<s[i]<<" ";
	}
	cout<<endl;
}
void reverse2(char *s,int n){
	char temp[n]; //create a temp array size of n;
	int j=0;;
	for(int i=n-1;i>=0;i--,j++){  // s shuzu daozhi fugei temp
		temp[j]=s[i];
	}
	for(int i=0;i<n;i++){ //temp zhengfuguolai s
		s[i]=temp[i];
	}
}
int main(){
	char s[]={'h','e','l','l','o'};
	int n=sizeof(s)/sizeof(s[0]);
	reverse(s,n);
	print(s,n);
	return 0;

}

版权声明:本文为m0_45864023原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。