user2199294
user2199294

Reputation:

Reverse word of full sentence

I want to print string in reverse format:

Input: My name is Archit Patel

Output: Patel Archit is name My.

I've tied the following but it displays as letaP tihcrA si eman ym.

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

Upvotes: 5

Views: 69927

Answers (20)

Rituraj Jana
Rituraj Jana

Reputation: 11

 public static string ReverseString(string s)
    {
        //1. Split String at space ' '
        var strDelimitedArray=s.Split(' ');
        /*2. Reverse the sequence of the new generated array i.e from 12345
        [My name is Archit Patel] to 54321 [Patel Archit is name My] and then join it to Form a String 
        from array of strings */
        var strReverseArray = strDelimitedArray.Reverse().Select(str => (new String(str.ToArray())));
        //3. Formulate the new string with spaces
        var strReverse= strReverseArray.Aggregate((x, y) => x + " " + y);
        return strReverse;
    }

Upvotes: 0

Vinay Dixit
Vinay Dixit

Reputation: 7

       string[] strArar = str.Split(" ");
        StringBuilder strb = new StringBuilder();            
        for(int j= strArar.Length-1; j>=0; j--)
        {
            strb.Append(strArar[j]);
            strb.Append(" ");
        }

        strb.ToString()

Upvotes: 0

William Macuga
William Macuga

Reputation: 1

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

Upvotes: -2

RK0703
RK0703

Reputation: 1

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

Upvotes: 0

CoderSam
CoderSam

Reputation: 551

You can use Stack for solving such queries:

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"

Upvotes: 1

Meenakshi Rana
Meenakshi Rana

Reputation: 545

Try this without in-built functions

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

Upvotes: 6

maxspan
maxspan

Reputation: 14157

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

Upvotes: 0

Neil Meyer
Neil Meyer

Reputation: 591

Here is an easy way

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

  1. You first create an array called sentence word and use the split method to populate the array with all your words. Note that space is used as a delimiter, telling the split method when exactly to split.
  2. You then use the Reverse method in the Array class to reverse the complete array.
  3. You then use the Join method of the string class to join your now reversed array into a string called newSentence.
  4. Finally the method then returns the newSentence string.

Upvotes: 1

Bilpesh
Bilpesh

Reputation: 21

I appreciate Rob Anderson answer, but it will reverse complete sentence, Just editing that

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 will be "Patel Archit is name My"

Upvotes: 2

Rob Anderson
Rob Anderson

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

Upvotes: -2

ronenfe
ronenfe

Reputation: 2405

This is my solution to an interview question if you need to do it in place. I use one more character for the swap. I assume space is only used as a separator.

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

Upvotes: 0

Bharath C N
Bharath C N

Reputation: 1

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

        }
    }
}

Upvotes: 0

RobIII
RobIII

Reputation: 8821

"please send me the code of this program."

Okay ...

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

Now: what have you learned?

Also, as Guffa points out, for versions below .Net 4.0 you'll need to add .ToArray() since string.Join doesn't have the correct overload in those versions.

Upvotes: 7

Calin Vlasin
Calin Vlasin

Reputation: 1433

This should do your job! OUTPUT: "Patel Archit is name 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();  
    }  

Upvotes: 2

nihnih
nihnih

Reputation: 61

If you want non-linq solution:

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

Upvotes: 0

Zhuhulo
Zhuhulo

Reputation: 11

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

Upvotes: 0

waqar habib
waqar habib

Reputation: 315

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

Upvotes: 0

Guffa
Guffa

Reputation: 700352

You would need to split the string into words and the reverse those instead of reversing the characters:

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

In framework 3.5:

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

In framework 2.0:

string[] words = text.Split(' ');
Array.Reverse(words);
text = String.Join(" ", words);

Upvotes: 20

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

You could try:

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

Upvotes: 1

Crowlix
Crowlix

Reputation: 1269

Use the split method to put it in an array

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

Then reverse the array with array.reverse

words = Array.Reverse(words);

Now you can print it with a for-each loop and add spaces

Hope this helps

Upvotes: 0

Related Questions