字符串按單詞反轉
/// <summary>
/// 我們將字符串input中,從input開始到end之間的子字符串反轉
/// </summary>
/// <param name="input"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <returns></returns>
public static void Revert(char[] input, int begin, int end)
{
if (input == null || input.Length < end || begin > end) throw new ArgumentException("Please check the input parameters.");
for (int first = begin, last = end - 1; first < last; first++, last--)
{
char temp = input[first];
input[first] = input[last];
input[last] = temp;
}
}
接下來我們需要一個方法來調用它,該方法接受一個字符數組,第一步先首尾交換,反轉字符串。然後我們尋找裏面的空格,再將單詞首尾依次交換:
public static void RevertWords(char[] input)
{
if (input != null && input.Length > 0)
{
Revert(input, 0, input.Length);
int begin = 0;
for (int index = begin; index < input.Length; index++)
{
if (input[index] == ' ')
{
int end = index;
Revert(input, begin, end);
begin = end + 1;
}
}
}
}
static void Main(string[] args)
{
char[] input = "I am student".ToArray();
RevertWords(input);
foreach (var c in input)
{
Console.Write(c);
}
}