5

我想以反向格式打印字符串:

输入: My name is Archit Patel

输出:Patel Archit is name My

我绑定了以下内容,但它显示为letaP tihcrA si eman ym.

public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}
4

19 回答 19

19

您需要将字符串拆分为单词并将其反转而不是反转字符:

text = String.Join(" ", text.Split(' ').Reverse())

在框架 3.5 中:

text = String.Join(" ", text.Split(' ').Reverse().ToArray())

在框架 2.0 中:

string[] words = text.Split(' ');
Array.Reverse(words);
text = String.Join(" ", words);
于 2013-03-26T10:03:56.940 回答
7

请把这个程序的代码发给我。”

好的 ...

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        string text = "My name is Archit Patel";

        Console.WriteLine(string.Join(" ", text.Split(' ').Reverse()));
    }
}

现在:你学到了什么?

此外,正如Guffa 指出的那样,对于 .Net 4.0 以下的版本,您需要添加,因为 string.Join在这些版本.ToArray()中没有正确的重载。

于 2013-03-26T10:04:57.620 回答
5

在没有内置函数的情况下试试这个

public string ReverseFullSentence(string inputString)
        {
            string output = string.Empty;
            string[] splitStrings = inputString.Split(' ');
            for (int i = splitStrings.Length-1; i > -1 ; i--)
            {
                output = output + splitStrings[i]+ " ";
            }
                return output;
        }
于 2019-05-30T10:49:07.717 回答
2

这应该做你的工作!输出:“Patel Archit 是我的名字”。

    static void Main(string[] args)  
    {  
        string sentence = "My name is Archit Patel";  
        StringBuilder sb = new StringBuilder();  
        string[] split = sentence.Split(' ');  
        for (int i = split.Length - 1; i > -1; i--)  
        {  
            sb.Append(split[i]);  
            sb.Append(" ");  
        }  
        Console.WriteLine(sb);  
        Console.ReadLine();  
    }  
于 2015-03-09T20:49:13.880 回答
1

你可以试试:

string[] words = "My name is Archit Patel".Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
IEnumerable<string> reverseWords = words.Reverse();
string reverseSentence = String.Join(" ", reverseWords);
于 2013-03-26T10:07:29.677 回答
1

您可以使用 Stack 来解决此类查询:

String input = "My name is Archit Patel";

        Stack<String> st = new Stack<String>(); 

        for(String word : input.split(" "))
            st.push(word); 

        Iterator it = st.iterator(); 

        while(it.hasNext()){
            System.out.print(st.pop()+" ");
        }
Output String: "Patel Archit is name My"
于 2019-06-21T12:37:31.103 回答
1

我很欣赏 Rob Anderson 的回答,但它会反转完整的句子,只需编辑它

string s = "My name is Archit Patel";

        string[] words = s.Split(' ');
        StringBuilder sb = new StringBuilder();

        for (int i = words.Length - 1; i >= 0; i--)
        {
            sb.Append(words[i]);
            sb.Append(" ");
        }

        Console.WriteLine(sb);

O/P 将是“Patel Archit is name My”

于 2017-04-01T17:43:31.273 回答
1

这是一个简单的方法

        public static string MethodExercise14Logic(string str)
        {
            string[] sentenceWords = str.Split(' ');
            Array.Reverse(sentenceWords);
            string newSentence = string.Join(" ", sentenceWords);
            return newSentence;
        }

  1. 您首先创建一个名为 sentence word 的数组,然后使用 split 方法将您的所有单词填充到数组中。请注意,空格用作分隔符,告诉 split 方法何时准确拆分。
  2. 然后使用 Array 类中的 Reverse 方法来反转整个数组。
  3. 然后,您使用字符串类的 Join 方法将您现在反转的数组连接到一个名为 newSentence 的字符串中。
  4. 最后,该方法返回 newSentence 字符串。
于 2018-11-02T10:29:44.877 回答
0

this.lblStringReverse.Text = 反向(this.txtString.Text);

private int NoOfWhiteSpaces(string s)
        {
            char[] sArray = s.ToArray<char>();
            int count = 0;
            for (int i = 0; i < (sArray.Length - 1); i++)
            {
                if (sArray[i] == ' ') count++;
            }
            return count;
        }
        private string Reverse(string s)
        {
            char[] sArray = s.ToArray<char>();
            int startIndex = 0, lastIndex = 0;
            string[] stringArray = new string[NoOfWhiteSpaces(s) + 1];
            int stringIndex = 0, whiteSpaceCount = 0;

            for (int x = 0; x < sArray.Length; x++)
            {
                if (sArray[x] == ' ' || whiteSpaceCount == NoOfWhiteSpaces(s))
                {
                    if (whiteSpaceCount == NoOfWhiteSpaces(s))
                    {
                        lastIndex = sArray.Length ;
                    }
                    else
                    {
                        lastIndex = x + 1;
                    }
                    whiteSpaceCount++;

                    char[] sWordArray = new char[lastIndex - startIndex];
                    int j = 0;
                    for (int i = startIndex; i < lastIndex; i++)
                    {
                        sWordArray[j] = sArray[i];
                        j++;
                    }

                    stringArray[stringIndex] = new string(sWordArray);
                    stringIndex++;
                    startIndex = x+1;
                }

            }
            string result = "";
            for (int y = stringArray.Length - 1; y > -1; y--)

                {
                    if (result == "")
                    {

                        result = stringArray[y];
                    }
                    else
                    {
                        result = result + ' ' + stringArray[y];
                    }
            }
            return result;
        }
于 2014-05-10T07:59:26.483 回答
0

使用 split 方法将其放入数组中

 string[] words = s.Split(' ');

然后用 array.reverse 反转数组

words = Array.Reverse(words);

现在您可以使用 for-each 循环打印它并添加空格

希望这可以帮助

于 2013-03-26T10:05:05.173 回答
0
    public static string reversewordsInsentence(string sentence)
    {
        string output = string.Empty;
        string word = string.Empty;
        foreach(char c in sentence)
        {
            if (c == ' ')
            {
                output = word + ' ' + output;
                word = string.Empty;
            }
            else
            {
                word = word + c;
            }
        }
        output = word + ' ' + output;
        return output;
    }
于 2014-07-14T18:07:01.850 回答
0

如果您想要非 linq 解决方案:

static string ReverseIntact(char[] input)
{
    //char[] input = "dog world car life".ToCharArray();
    for (int i = 0; i < input.Length / 2; i++)
    {//reverse the expression
        char tmp = input[i];
        input[i] = input[input.Length - i - 1];
        input[input.Length - i - 1] = tmp;
    }
    for (int j = 0, start = 0, end = 0; j <= input.Length; j++)
    {
        if (j == input.Length || input[j] == ' ')
        {
            end = j - 1;
            for (; start < end; )
            {
                char tmp = input[start];
                input[start] = input[end];
                input[end] = tmp;
                start++;
                end--;
            }
            start = j + 1;
        }
    }
    return new string(input);
}
于 2015-01-14T21:03:46.877 回答
0
public string GetReversedWords(string sentence)
        {
            try
            {
                var wordCollection = sentence.Trim().Split(' ');
                StringBuilder builder = new StringBuilder();
                foreach (var word in wordCollection)
                {
                    var wordAsCharArray = word.ToCharArray();
                    Array.Reverse(wordAsCharArray);
                    builder.Append($"{new string(wordAsCharArray)} ");
                }

                return builder.ToString().Trim();
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
于 2019-01-26T00:43:36.247 回答
0
// This Method will reverse word-of-full-sentence without using built-in methods.
public void revSent()
        {
            string s = "My name is Archit Patel";
            List<string> Words = new List<string>(s.Split(' '));
            List<string> Rev = new List<string>();
            for(int i=Words.Count-1;i>=0;i--)
            {
                Rev.Add(Words.ElementAt(i));
            }
            Console.WriteLine(string.Join(" ", Rev));
        }
于 2021-07-28T07:59:42.867 回答
0

如果您需要就地进行,这是我对面试问题的解决方案。我使用了另外一个字符进行交换。我假设空格仅用作分隔符。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder("abcd efg hijk");
        Reverse(sb, 0 , sb.Length - 1);
        Console.WriteLine(sb);
        ReverseWords(sb);
        Console.WriteLine(sb);
        ReverseWordOrder(sb);
        Console.WriteLine(sb);
    }
    static void Reverse(StringBuilder sb, int startIndex, int endIndex)
    {

        for(int i = startIndex; i <= (endIndex - startIndex) / 2 + startIndex; i++)
        {
            Swap(sb,i, endIndex + startIndex - i);
        }
    }

    private static void Swap(StringBuilder sb, int index1, int index2)
    {
        char temp = sb[index1];
        sb[index1] = sb[index2];
        sb[index2] = temp;
    }

    static void ReverseWords(StringBuilder sb)
    {
        int startIndex = 0;
        for (int i = 0; i <= sb.Length; i++)
        {
            if (i == sb.Length || sb[i] == ' ')
            {
                Reverse(sb, startIndex, i - 1);
                startIndex = i + 1;
            }
        }
    }
    static void ReverseWordOrder(StringBuilder sb)
    {
        Reverse(sb, 0, sb.Length - 1);
        ReverseWords(sb);
    }
}
}
于 2016-10-06T20:15:39.160 回答
0
namespace Reverse_the_string
{
    class Program
    {
        static void Main(string[] args)
        {

           // string text = "my name is bharath";
            string text = Console.ReadLine();
            string[] words = text.Split(' ');
            int k = words.Length - 1;
            for (int i = k;i >= 0;i--)
            {
                Console.Write(words[i] + " " );

            }

            Console.ReadLine();

        }
    }
}
于 2016-09-13T16:54:03.047 回答
0

不使用拆分和循环

public static string ReverseString(string s)
{
    string strToReverse = s;
    int fi = strToReverse.IndexOf(' ');
    int li = strToReverse.LastIndexOf(' ');
    string fp = strToReverse.Substring(0, strToReverse.IndexOf(' ')).TrimStart(' '); ;
    string mp = strToReverse.Substring(fi, li - fi).Trim(' ');
    string ep = strToReverse.Substring(strToReverse.LastIndexOf(' ', strToReverse.Length - 1)).TrimStart(' ');
    return ep + " " + mp + " " + fp;
}
于 2021-10-24T09:14:42.297 回答
-2
 static void Main(string[] args)
        {
            string str = "the quick brown fox";
            string[] arr = str.Split(' ');
            for (int i = arr.Length - 1; i >= 0; i--)
            {
                Console.Write(arr[i] + " ");
            }


            Console.Read();
        }
于 2021-07-29T10:04:41.630 回答
-2
        string s = "this is a test";

        string[] words = s.Split(' ');
        StringBuilder sb = new StringBuilder();

        for (int i = words.Length - 1; i >= 0; i--)
        {
            for (int j = words[i].Length -1; j >= 0;j--)
            {
                sb.Append(words[i][j]);
            }
            sb.Append(" ");
        }

        Console.WriteLine(sb);
于 2017-02-28T14:41:21.620 回答