【问题标题】:Why does this print "Hello World" and not "dlroW olleH"为什么这会打印“Hello World”而不是“dlroW olleH”
【发布时间】:2015-12-04 10:46:54
【问题描述】:
namespace Lab1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] LabOne = { "Hello World" };
            for (int i = LabOne.Length - 1; i >= 0; i--)
            {
                Console.WriteLine(LabOne[i]);
                Console.ReadLine();
            }
        }
    }
}

【问题讨论】:

  • 您是否尝试在调试器中单步执行您的代码?你认为这个数组有多少个元素?
  • 您不是在遍历字符串中的字符,而是在遍历一个 1 元素的字符串数组。因此只打印那 1 个字符串。
  • 字符串可以被视为数组。所以如果你有string LabOne = "Hello World";,那么你可以指向它的字符,比如LabOne[i]。
  • 正如其他人所说,在您的应用程序中放置一个断点并查看您的int i 的值。它的值应该是1,因为您的string[] 中只有1 个元素,即完整的字符串“Hello World”。所以它只循环一次并访问该数组中的第一个(巧合的是,最后一个)项目,即“Hello World”。搜索如何遍历字符串中的每个字符。

标签: c# arrays string reverse


【解决方案1】:

您的问题是,您有一个字符串数组,并且您正在从数组的后部打印每个元素。但是,数组中只有一个元素:字符串“Hello World”。所以后面就是前面。我想这就是你要找的。​​p>

namespace Lab1
{
    class Program
    {
        static void Main(string[] args)
        {
            string LabOne = "Hello World";
            for (int i = LabOne.Length - 1; i >= 0; i--)
            {
                Console.WriteLine(LabOne.[i]);
            }
        }
    }
}

【讨论】:

  • 你不应该在这里使用ElementAt。您应该使用索引器。您只是将 O(n) 操作不必要地变成了 O(n^2) 操作。
  • Evan,这也会打印“Hello World”
【解决方案2】:

我知道这是一个老问题。

        string str = "hello World!";          
        char[] a = str.ToArray();
        StringBuilder builder = new StringBuilder();
        for (int i = str.Length -1 ; i > 0; i--)
        {
            builder.Append(a[i]);                
        }

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 2023-02-20
    • 2018-10-31
    • 2014-01-10
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多