動機:
對於給你一個字串,
再要求你寫個function去reverse它,
要如何寫呢?!
說明:
利用 Dev-C++ 免費軟體,
再撰寫相關的程式即可達到要求, 程式碼如下:
(若重點是要求 algorithm 及 performance 的話,
可能程式碼就要另外思考如何改變了)
#include <cstdlib>
#include <iostream>
using namespace std;
static char str[] = "I am a good boy";
int reverse(int pos)
{
// Here I am calculating strlen(str) everytime.
// This can be avoided by doing this computation
// earlier and storing it somewhere for later use.
if(pos < (strlen(str) / 2))
{
char ch;
// Swap str[pos] and str[strlen(str) - pos - 1]
ch = str[pos];
str[pos] = str[strlen(str) - pos - 1];
str[strlen(str) - pos - 1] = ch;
// Now recurse!
reverse(pos + 1);
}
}
int main(int argc, char *argv[])
{
printf("\nOriginal string : [%s]", str);
// Call the recursion function
reverse(0);
printf("\nReversed string : [%s]\n", str);
system("PAUSE");
return EXIT_SUCCESS;
}
參攷: Write a C program to reverse a string.
執行檔下載連結: https://docs.google.com/leaf?id=0B_4eUrknq7N1NGY0N2Y2ZDQtMjYzYy00MzZjLTgxZTMtOTQ5MzM5YTUwMjk4&hl=zh_TW
留言