以首位交換的方法交換字符串中以'A'開頭和以'N'結尾的單詞

題目:以首位交換的方法交換字符串中以'A'開頭和以'N'結尾的單詞

           輸入:AM I OLDER THAN YOU
           輸出:THAN I OLDER AM YOU 

//輸入:AM I OLDER THAN YOU
//輸出:THAN I OLDER AM YOU 
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void exchange(const char *pIn,char *pOut){
	char aa[200];
	char temp[10][10],exchange[10];
	int num=0,i,j,len;
	int head,tail;
	while(*pIn!='\0'){//將字符串中的單詞分開存儲在二維數組中 開始 
		if((*pIn>='a'&&*pIn<='z')||(*pIn>='A'&&*pIn<='Z')){
			i=0;
			temp[num][i]=*pIn;
			i++;
			pIn++;
			while((*pIn>='a'&&*pIn<='z')||(*pIn>='A'&&*pIn<='Z')){
				temp[num][i]=*pIn;
				pIn++; 
				i++;
			} 
			temp[num][i]='\0';
			num++;
		}else{
			pIn++;
		}
	} //將字符串中的單詞分開存儲在二維數組中 結束 
	head=0;
	tail=num-1;
	while(head<tail){
		if(temp[head][0]=='A'){
			len=strlen(temp[tail]);
			if(temp[tail][len-1]=='N'){
				strcpy(exchange,temp[head]);
				strcpy(temp[head],temp[tail]);
				strcpy(temp[tail],exchange);
				head++;
				tail--;
			}else{
				tail--;
			}
		}else{
			head++;
		}
	}
	for(i=0;i<num;i++){
		strcat(pOut,temp[i]);
		strcat(pOut," "); 
	}
} 
int main(){
	const char *pIn="AM I OLDER THAN YOU";
	char *pOut=calloc(sizeof(strlen(pIn)),1);
	exchange(pIn,pOut);
	puts(pIn);
	puts(pOut);
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章