C語言 將一句話反過來顯示(20點)
題目是
要將一句英文句子反過來
例子:
輸入:you can't cage a swallow can't you?
顯示:you can't swallow a cage can't you?
要用迴圈將句子存在一個一維陣列裡
再用第二個迴圈把單子由後往前顯示出來
句子結尾的標點符號(句號、問號、驚嘆號等)
要獨立出來顯示在最後面
下面的例子是錯誤的:
輸入:you can't cage a swallow can't you?
顯示:?you can't swallow a cage can't you
最後的要求是 The program uses a pointer instead of an integer to keep track of the current position in the array that contains the sentence.
就是要用指標來取代數字...(英文看得懂不會翻中文一一")
先謝謝各位了!
2 個解答
- AllenLv 41 0 年前最佳解答
#include<stdio.h>
#include<stdlib.h>
void printWord(char *);
int main(void){
char stc[50];
char *ptr;
int i=0,lw=0;
printf("輸入:");
gets(stc); //讀取字串
ptr=&stc[0]; //將指標指到字串陣列的第一個位置
while(*ptr!='?'&&*ptr!='.'&&*ptr!='!'&&*ptr!='\0'){
ptr++; //將指標移動到字串的最後一個字元位置(字元!?.或是沒有符號,則指到字串結束點)
i++; //用i儲存字串長度
lw++; //lw用來儲存最後一個字元的位置
}
printf("顯示:");
while(i>=0){ //指標由後往前走,用i來判定是否已到字串第一個字元
if(*ptr==' '||i==0){ //若指標內的字元為空白字元則呼叫printWord
if(i==0){ //若指標已指到字串的第一個字元則列印出第一個單字
while(*ptr!='?'&&*ptr!='.'&&*ptr!='!'&&*ptr!=' '&&*ptr!='\0'){
printf("%c",*ptr);
ptr++;
}
}
else
printWord(ptr);
}
ptr--; //讓指標由字串最後往前指,i亦隨之移動
i--;
}
printf("%c",stc[lw]); //列印出字串最後一個字元,亦即符號字元!?.
printf("\n");
return 0;
}
void printWord(char *pt){ //列印單字的函數,宣告一指標pt,其所指位置與傳入的ptr一樣
pt++; //所傳入的ptr為指到空白字元的位置,故pt+1
while(*pt!='?'&&*pt!='.'&&*pt!='!'&&*pt!=' '&&*pt!='\0'){
printf("%c",*pt); //指標往前列印出字元,遇到符號字元或空白字元則停止
pt++;
}
printf(" "); //補上空白字元
}
- 汪汪 汪汪Lv 71 0 年前
用 Loop 也不會太長~~ 問題不在 Loop 在XXX身上.....
#include <stdio.h>
#include <stdlib.h>
int main(void){
char st[100],*p,pun;
printf("輸入:"); gets(st); p=st;
printf("顯示:"); while (*p!='\0') p++;
while (p!=st) {
if (*p=='?' || *p=='.' || *p=='!') {pun=*p; *p='\0';}
if (*p==32) {printf("%s ",p+1); *p='\0';}
p--;
}
printf("%s%c",p,pun);
system("pause");
return 0;
}
printf("%s%c",p,pun);
system("pause");
return 0;
}