作者MOONRAKER (㊣康少校是死到哪裡去了)
看板C_and_CPP
標題Re: [問題] 反轉字串裡面的字元
時間Thu Oct 25 21:58:22 2012
以下是我的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
推 ledia:用 fwrite 不用 substr .... XD 10/25 22:04
→ ledia:這樣就是 O(1) extra space 了~ 10/25 22:05
→ MOONRAKER:順便抱怨一下,我沒想到cstring居然沒有substr() 10/26 04:23
→ MOONRAKER:這個substr其實是把strncpy包起來… 10/26 04:24
推 changyuheng:我的版本似乎快了一點點喔! 10/26 17:30
→ MOONRAKER:我又沒有說比你快。這種簡單的事有什麼好比的。 10/26 18:17
推 ledia:btw, changyuheng 的程式有小錯, 沒有 initialize 的變數 10/26 22:30
推 changyuheng:請問哪裡錯? 10/26 22:37
推 changyuheng:感謝 10/26 23:08
→ loveme00835:沒什麼要求的話比這個真的很無聊... 10/26 23:08
推 changyuheng:原 po 的寫法好像會比較快,但驗證後並非如此。 10/30 10:52
推 changyuheng:這整串在討論不就是效率,為什麼說無聊? 10/30 10:55