需求:有一个字符串为”hello world!”,将其倒序打印输出。
class Program
{
static void Main(string[] args)
{
string str = "hello world!";
char[] chars = str.ToCharArray();
Console.WriteLine(chars);
for (int i = 0; i <= chars.Length-1; i++)
{
Console.Write(chars[chars.Length-i-1]);
}
}
}
上面的代码基本实现了倒序输出的功能,但是时间复杂度高。
class Program
{
static void Main(string[] args)
{
string str = "hello world!";
char[] chars = str.ToCharArray();
//Console.WriteLine(chars);
//Console.WriteLine(chars.Length);
//for (int i = 0; i <= chars.Length-1; i++)
//{
// Console.Write(chars[chars.Length-i-1]);
//}
Array.Reverse(chars);
Console.Write(chars);
}
}
这段代码中使用Reverse方法便可以直接将数组中的元素倒序排列。