動機:
對於給你一個字串,
再要求你寫個function去reverse它,
要如何寫呢?!
說明:
利用 Microsoft Visual C# 2008 Express 免費軟體,
再撰寫相關的程式即可達到要求, 程式碼如下:
(若重點是要求 algorithm 及 performance 的話,
可能程式碼就要另外思考如何改變了)
using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
namespace ConsoleApplicationReverseAString
{
class Program
{
static char[] str = new char[] {'I',' ','a','m',' ','a',' ','g','o','o','d',' ','b','o','y'};
private static void Reverse(int pos)
{
if (pos < (str.Length / 2))
{
char ch;
// Swap str[pos] and str[str.Length - pos - 1]
ch = str[pos];
str[pos] = str[str.Length - pos - 1];
str[str.Length - pos - 1] = ch;
// Now recurse!
Reverse(pos + 1);
}
}
private static void ListString()
{
for (int i = 0; i < str.Length; i++) {
Console.Write(str[i]);
}
}
public static void Pause() {
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
}
static void Main(string[] args)
{
Console.Write("Original string : ");
// List original string
ListString();
// Call the recursion function
Reverse(0);
// List new line
Console.WriteLine();
Console.Write("Reversed string : ");
// List reversed string
ListString();
// List new line
Console.WriteLine("\n");
// Pause
Pause();
}
}
}
參攷: Write a C program to reverse a string.
執行檔下載連結: https://docs.google.com/leaf?id=0B_4eUrknq7N1YjJiMDUxMTctN2IxNS00MTY1LTgyZjItNzJkNTUzYTMxNzdm&hl=zh_TW
留言