Re: [問題] C做字串互換
※ 引述《sagwow (不是我)》之銘言:
: 問題(Question):
: 字串互換
: 餵入的資料(Input): apple dog
: 預期的正確結果(Expected Output):dog apple
: 補充說明(Supplement):
: 我宣告char a[100][1000],想交換其中a[0]和a[1]兩個字串,
: 想請問有沒有不用一個字元一個字元交換的方法。
GitHub Gist: https://gist.github.com/anonymous/ea41f753a335f34a3ec458f730c8f499
不一定要用二維陣列去處理,有 in-place 的 recursive 算法提供參考
大致上的做法就是 先對原字串反轉一次,再對子字串反轉一次就可以了
#include <stdio.h>
#include <string.h>
char *swapstr_rec(char *str, int begin, int end, int first)
{
while (begin < end - 1)
{
char tmp = str[begin];
str[begin++] = str[--end];
str[end] = tmp;
}
end += begin;
if (!first)
return NULL;
for (int idx = 1, prv = 0; idx <= end; idx++)
{
if (((str[idx] == ' ' || str[idx] == '\0') ^
(str[idx - 1] == ' ' || str[idx - 1] == '\0')))
swapstr_rec(str, prv, idx, 0), prv = idx;
}
return str;
}
char *swapstr(char *str)
{
return swapstr_rec(str, 0, strlen(str), 1);
}
int main(void)
{
char str[] = "apple dog";
printf("%s\n", swapstr(str));
}
--
作者 llyre (r^^||) 看板 Soft_Job
標題 Fw: [台北] 台北360徵Linux/Android安全研究員
推
07/16 17:40,
07/16 17:40
推
07/16 17:54,
07/16 17:54
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.243.51.36
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1473178449.A.BE7.html
推
09/07 15:33, , 1F
09/07 15:33, 1F
→
09/07 16:36, , 2F
09/07 16:36, 2F
→
09/07 16:38, , 3F
09/07 16:38, 3F
推
09/07 20:44, , 4F
09/07 20:44, 4F
→
09/07 23:11, , 5F
09/07 23:11, 5F
推
09/08 02:27, , 6F
09/08 02:27, 6F
→
09/08 02:28, , 7F
09/08 02:28, 7F
→
09/08 03:07, , 8F
09/08 03:07, 8F
→
09/08 03:08, , 9F
09/08 03:08, 9F
→
09/08 03:09, , 10F
09/08 03:09, 10F
→
09/08 03:11, , 11F
09/08 03:11, 11F
→
09/08 03:12, , 12F
09/08 03:12, 12F
→
09/08 03:12, , 13F
09/08 03:12, 13F
→
09/08 03:13, , 14F
09/08 03:13, 14F
※ 編輯: Hazukashiine (1.160.123.188), 09/08/2016 03:14:44
→
09/08 03:18, , 15F
09/08 03:18, 15F
→
09/08 03:19, , 16F
09/08 03:19, 16F
→
09/08 03:21, , 17F
09/08 03:21, 17F
推
09/08 13:33, , 18F
09/08 13:33, 18F
→
09/08 13:34, , 19F
09/08 13:34, 19F
推
09/08 14:39, , 20F
09/08 14:39, 20F
討論串 (同標題文章)