反句全句

时间:2013-03-26 10:01:47

标签: c#

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

输入: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);
}

18 个答案:

答案 0 :(得分:15)

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

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);

答案 1 :(得分:6)

please send me the code of this program”。

好的......

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 points out,对于.Net 4.0以下的版本,您需要添加.ToArray(),因为string.Join在这些版本中没有the correct overload

答案 2 :(得分:2)

这应该可以胜任你的工作!输出:" Patel Archit名为My"。

    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();  
    }  

答案 3 :(得分:1)

你可以尝试:

string[] words = "My name is Archit Patel".Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
IEnumerable<string> reverseWords = words.Reverse();
string reverseSentence = String.Join(" ", reverseWords);

答案 4 :(得分:1)

我很欣赏罗伯·安德森的回答,但它会反转完整的句子, 只需编辑

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是我的名字”

答案 5 :(得分: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);
    }
}
}

答案 6 :(得分: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));
        }

答案 7 :(得分:0)

您可以使用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"

答案 8 :(得分:0)

在没有内置功能的情况下尝试此操作

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;
        }

答案 9 :(得分: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);
            }
        }

答案 10 :(得分:0)

这是一种简单的方法

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

  1. 您首先创建一个称为句子单词的数组,然后使用split方法将所有单词填充到数组中。请注意,空格用作定界符,告诉split方法何时精确拆分。
  2. 然后在Array类中使用Reverse方法来反转整个数组。
  3. 然后使用字符串类的Join方法将现在反转的数组连接到名为newSentence的字符串中。
  4. 最后,该方法然后返回newSentence字符串。

答案 11 :(得分: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();

        }
    }
}

答案 12 :(得分: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);
}

答案 13 :(得分: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;
    }

答案 14 :(得分:0)

this.lblStringReverse.Text = Reverse(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;
        }

答案 15 :(得分:0)

使用split方法将其放入数组

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

然后用array.reverse

反转数组
words = Array.Reverse(words);

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

希望这有帮助

答案 16 :(得分:-1)

        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);

答案 17 :(得分:-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();
        }