Re: [問題] 反轉字串裡面的字元
以下是我的reverse-sentence-by-word,如果我沒有誤解題目意思的話。
只有輸出,沒有存回去,上班再偷一點時間大概可以寫出來,可是要做到
O(0)或O(1) extra memory usage實在太麻煩了,而且會很浪費時間。大
概只適用於那種一個byte都榨不出來的狀況吧。
http://ideone.com/QICluS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define S_SPACE 0
#define S_CHAR 1
void substr(char buf[], char *str, int wstart, int wend) {
strncpy(buf, str + wstart, wend - wstart + 1);
buf[wend - wstart + 1] = '\0';
}
main()
{
char *s = "Mark Twain: Always tell the truth and you needn't remember everything.";
int i, j, state, newstate;
char *caption;
char status[80], wordbuf[80];
int wordstart, wordend, wordlen;
i = strlen(s);
state = isspace(s[i]) ? S_SPACE : S_CHAR;
--i;
wordend = i;
while (i >= 0) {
newstate = isspace(s[i]) ? S_SPACE : S_CHAR;
if (newstate != state) {
if (newstate == S_SPACE) {
substr(wordbuf, s, i + 1, wordend);
printf("%s ", wordbuf);
}
else {
wordend = i;
}
state = newstate;
}
else {
}
--i;
}
// Dump the remains if still in char state
if (state == S_CHAR) {
substr(wordbuf, s, 0, wordend);
printf("%s\n", wordbuf);
}
return 0;
}
--
從前有個馬鈴薯王國 有個高貴偉大的國王
有的人尊敬他 有的人畏懼他 但有個人敢看不起他不只是一條龍
嘿呵 快出動 去征服 去擺平 嘿呵 快出征 去征服那條龍
嘿呵 快出動(宰了它!轟了它!)嘿呵 快出征 去征服那條龍
:■ Potatoes and Dragons (C)Alphanim France 2004-05 :.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.45.203.111
推
10/25 22:04, , 1F
10/25 22:04, 1F
→
10/25 22:05, , 2F
10/25 22:05, 2F
→
10/26 04:23, , 3F
10/26 04:23, 3F
→
10/26 04:24, , 4F
10/26 04:24, 4F
推
10/26 17:30, , 5F
10/26 17:30, 5F
→
10/26 18:17, , 6F
10/26 18:17, 6F
推
10/26 22:30, , 7F
10/26 22:30, 7F
推
10/26 22:37, , 8F
10/26 22:37, 8F
→
10/26 22:45, , 9F
10/26 22:45, 9F
推
10/26 23:08, , 10F
10/26 23:08, 10F
→
10/26 23:08, , 11F
10/26 23:08, 11F
推
10/30 10:52, , 12F
10/30 10:52, 12F
推
10/30 10:55, , 13F
10/30 10:55, 13F
討論串 (同標題文章)