1. 程式人生 > >字串反轉--句子反轉和單詞反轉

字串反轉--句子反轉和單詞反轉

#include <iostream>
using namespace std;
//整個句子反轉
void allReverse(char s[]){
	int i=0,j=strlen(s)-1;//別忘了減1
	char temp ;
	while(j > i){
		temp = s[i];s[i]=s[j];s[j]=temp;
		j--;
		i++;
	}
	cout<<s<<endl;
}//allReverse

//所有單詞反轉
void partialReverse(char s[]){
	int i=0,begin,end;
	char temp;
	while(s[i]){
		if(s[i]!=' '){
			begin = i;
			while(s[i] && s[i]!=' '){
				i++;
			}
			i=i-1;
			end = i;
	    }//if
		while(begin<end){
		temp = s[begin];s[begin]=s[end];s[end]=temp;
		begin++;
		end--;
		}//while
		i++;
	}//while
	cout<<s<<endl;
}//partialReverse


int main(){

	char s[50]="SHE LOVE C++";
	allReverse(s);
	partialReverse(s);
}

//++C EVOL EHS
//C++ LOVE SHE
//請按任意鍵繼續. . .