反转字符串,单词内部顺序不变

/*
输入: we are friends.
反转后: friends are we.

*/

#include <stdio.h>
#include <string.h>
 /*
 函数功能: 反转字符串,单词内部顺序不变;
 参数: 输入的字符串;
 返回值: 空。
 */
void word_invert(char *s){

	int len = strlen(s);
	int i =0 ;
	int begin =0, end = 0;

	char tmp;
	// invert string first;
	for ( i = 0; i < len/2; i++){
		tmp = s[i];
		s[i] = s[len - 1 - i];
		s[len - 1 - i] = tmp;
	}
    
	i = 0;
	while(s[i] != '\0'){
		if(s[i] != ' '){
			if ( i >0 && s[i-1] == ' ')
				begin = i;
		}
		else{
			if( i > 0 && s[i-1] !=' '){
				end = i - 1;
				while(begin <= end){
					tmp = s[begin];
					s[begin] = s[end];
					s[end] = tmp;
					begin++;
					end--; 
				}
			}
		}
		i++;
	}

	end = i - 1;
	while(begin <= end){
		tmp = s[begin];
		s[begin] = s[end];
		s[end] = tmp;
		begin++;
		end--; 
	}

}


int main(){
	char s[100];
	printf("input string :  ");
	gets(s);
	word_invert(s);
	printf("invert string: %s\n",s);
	return 0;
}


你可能感兴趣的:(反转字符串,单词内部顺序不变)