【问题标题】:c# Reversing words in a string using single loop without using reverse function and stackc#在不使用反向函数和堆栈的情况下使用单循环反转字符串中的单词
【发布时间】:2017-09-10 17:57:25
【问题描述】:

我尝试用单循环编写反转字符串中每个单词的逻辑,但我没有让它工作。您能否提供使用单循环而不使用反向函数来反转字符串中每个单词的逻辑。

输入:

欢迎来到这个世界

输出:

emocleW ot eht dlrow

我的逻辑有两个循环:

class Program
    {
        static void Main(string[] args)
        {
            string input = string.Empty;
            input = Console.ReadLine();
            string[] strarr=input.Split(' ');
            StringBuilder sb = new StringBuilder();
            foreach (string str in strarr)
            {
                sb.Append(fnReverse(str));
                sb.Append(' ');
            }
            Console.WriteLine(sb);
            Console.Read();
        }
        public static string fnReverse(string str)
        {
            string result = string.Empty;
            for (int i = str.Length-1; i >= 0; i--)
                result += str[i];
            return result;
        }
    }

【问题讨论】:

  • 你为什么不简单地将输入字符串传递给你的函数 fnReverse 它应该可以工作

标签: c# string text reverse


【解决方案1】:
    string strIn = "Welcome to the world";
    string strTmp = "";
    string strOut = "";

    for (int i=strIn.Length-1; i>-1; i--)
    {
        if (strIn[i] == ' ')
        {
            strOut = strTmp + " " + strOut;
            strTmp = "";
        }
        else
        {
            strTmp += strIn[i];
        }   
    }
    strOut = strTmp + " " + strOut;

给出结果“emocleW ot eht dlrow”

【讨论】:

  • 这和我的回答一样
  • @AshkanMobayenKhiabani 它看起来和你的一样,虽然这似乎是在你的被编辑使用这种方法之前发布的。我建议你们两个独立得出相同的答案。
  • @AshkanMobayenKhiabani 是的,抱歉,这是我在注销之前发布的最后一件事,然后看到您已将您的内容编辑为相同。伟大的思想和所有的想法都是一样的......
【解决方案2】:
 string input = Console.ReadLine();
            string result = "";
            string tmp = "";
            for (int i = input.Length - 1; i >= 0; i--)
            {
                if (input[i] == ' ')
                {
                    result =  tmp + " " + result;
                    tmp = "";
                }
                else
                    tmp += input[i];
            }
            result = tmp + " " + result;
            Console.WriteLine(result);

这里是DEMO

【讨论】:

  • 感谢您的回复,但如果我考虑所有程序,我应该只使用一个循环,但在我的代码中我使用了 2 个循环。
  • 你能告诉我这两个循环是什么吗?我不明白。只有一个循环用于反转字符串
  • @AshkanMobayenKhiabani 我认为他在谈论循环每个单词的foreach
  • 你不能用单循环。例如,您可以使用 linq 查询隐藏循环,但它仍然会存在
  • @Anandkumar 现在我明白你的意思了。请看看我编辑的答案
猜你喜欢
  • 1970-01-01
  • 2013-01-19
  • 2017-06-15
  • 1970-01-01
  • 2015-11-22
  • 2021-09-03
  • 2018-03-09
  • 2013-03-11
  • 1970-01-01
相关资源
最近更新 更多