none
reverse string without using any C# function

    Question

  • hi

    i want to reverse string just like

    input is "My Name is Khan"

    output is "Khan is Name My"

    my function is

    public sring reverse()

    {

    string str=" my name is khan";

    string str1=string.empty;

    string[] strArr=str.split(' ');

    for (int i=strArr.length; i>0; i--)

    {

    str1=str1+strArr[i]+" ";

    }

    return str1;

    }

    this is right function to reverse string  as i want

    i don't to use split function as we used in my code str.split(' ');

    so please give me logic how we can reverse a string without using split function

    thanks in advance 

    Thursday, September 15, 2011 3:58 PM

Answers

  • Hi,

    Your solution for your question should be the best.

    Maybe you can override the Method string reverse(string original){...} and use your solutions here. After that, whenever you want to reserve the string, just call the function.

    Hope it helps!


    Knowledge will change the destiny.
    • Proposed as answer by Neddy Ren Tuesday, September 20, 2011 3:47 AM
    • Marked as answer by Neddy Ren Monday, September 26, 2011 2:22 AM
    Monday, September 19, 2011 8:26 AM
  • you can do as follows to reverse words in a string!

    string value = "My Name is ehsan";
    string reverse = string.Empty;
    
    char chSplit = ' ';
    
    string[] words = value.Split(new char[] { chSplit }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string word in words)
    {
        reverse = word + chSplit + reverse;
    }
    


    Any fool can know. The point is to understand.(Albert Einstein)
    • Marked as answer by Neddy Ren Monday, September 26, 2011 2:22 AM
    Monday, September 19, 2011 8:51 AM

All replies

  • Hi,

     try it this way:

    Console.WriteLine("Pleae enter a string, print enter to end");
    string input = Console.ReadLine();
    StringBuilder sb = new StringBuilder();
    int i = input.Length-1;
    while (i != - 1)
    {
          sb.Append(input[i--]);
    }
    Console.WriteLine("Reverse stirng is " + sb.ToString());
    



    Mitja
    Thursday, September 15, 2011 4:06 PM
  • Or:

        public string Reverse(string str)
        {
                int len = str.Length;
                char[] arr = new char[len];
    
                for (int i = 0; i < len; i++)
                {
                       arr[i] = str[len - 1 - i];
                }
                return new string(arr);
        }
    



    Mitja
    • Proposed as answer by Adavesh Friday, September 16, 2011 5:47 AM
    Thursday, September 15, 2011 4:10 PM
  •         public string Reverse(string str)
            {
                return new string(str.Reverse().ToArray());
            }
    

    Thursday, September 15, 2011 4:41 PM
  •         public string Reverse(string str)
            {
                return new string(str.Reverse().ToArray());
            }
    

    He said no C# functions!
    Mitja
    Thursday, September 15, 2011 5:49 PM
  • The do it without C# functions,  you'll have to use a different language.  Use VB.NET.
    Thursday, September 15, 2011 5:59 PM
  •         public string Reverse(string str)
            {
                return new string(str.Reverse().ToArray());
            }
    

    He said no C# functions!
    Mitja

    Capitalize String.
    • Edited by JohnWein Thursday, September 15, 2011 6:02 PM
    Thursday, September 15, 2011 6:01 PM
  • Hello,

    Test my code!

    string text = "my name is Ehsan!";
    string reverse = string.Empty;
    foreach (char ch in text)
    {
        reverse = ch + reverse;
    }
    



    Any fool can know. The point is to understand.(Albert Einstein)
    • Proposed as answer by Adavesh Friday, September 16, 2011 5:46 AM
    Friday, September 16, 2011 5:27 AM
  • Hello,

    Test my code!

    string text = "my name is Ehsan!";

    string reverse = string.Empty;

    foreach (char ch in text)

    {

        reverse = ch + reverse;

    }

    Beautiful. You can't get much simpler than this (without using builtin functions.)


    Please mark this post as answer if it solved your problem. Happy Programming!
    • Proposed as answer by Adavesh Friday, September 16, 2011 5:46 AM
    • Unproposed as answer by Adavesh Friday, September 16, 2011 5:46 AM
    Friday, September 16, 2011 5:46 AM
  • All you guys have shown code that totally reverses the string, and that's not what the OP wanted.

    "My Name is Bonnie" should end up being "Bonnie is Name My". With the code that's been shown thusfar (except for the OP's code with the use of the .Split() method), the result would be "einnoB si emaN yM". That's not what he wanted.

    @nitinsharma1983 -- what the heck is wrong with using .Split() and why the heck would you not want to take advantage of the capabilities of the language?
    ~~Bonnie Berent [C# MVP]

    geek-goddess-bonnie.blogspot.com
    Saturday, September 17, 2011 11:41 PM
  • Hi,

    Your solution for your question should be the best.

    Maybe you can override the Method string reverse(string original){...} and use your solutions here. After that, whenever you want to reserve the string, just call the function.

    Hope it helps!


    Knowledge will change the destiny.
    • Proposed as answer by Neddy Ren Tuesday, September 20, 2011 3:47 AM
    • Marked as answer by Neddy Ren Monday, September 26, 2011 2:22 AM
    Monday, September 19, 2011 8:26 AM
  • you can do as follows to reverse words in a string!

    string value = "My Name is ehsan";
    string reverse = string.Empty;
    
    char chSplit = ' ';
    
    string[] words = value.Split(new char[] { chSplit }, StringSplitOptions.RemoveEmptyEntries);
    foreach (string word in words)
    {
        reverse = word + chSplit + reverse;
    }
    


    Any fool can know. The point is to understand.(Albert Einstein)
    • Marked as answer by Neddy Ren Monday, September 26, 2011 2:22 AM
    Monday, September 19, 2011 8:51 AM
  • Here is another approach using C#:  http://wp.me/pRJom-5A
    • Edited by hectorea Wednesday, August 01, 2012 6:57 AM
    Wednesday, August 01, 2012 6:50 AM

  • string MainString = "Windows 8 rocks all over the World for its Metro Design"

    string[] splitedstring = MainString.Split(' ');

    string rev = "";

    foreach (string str in splitedstring)

                {

    for(int i=splitedstring.Length-1;i>=0;i--)

                {

                    rev = rev + splitedstring[i] + " ";

                }

               }

    Console.WriteLine(rev);

    Tested Properly.....

     

              

    Wednesday, November 21, 2012 12:43 PM
  •  /**Reverse a Sentence without using C# inbuilt functions (except String.Length property, m not going to write code for this small functionality )*/
            const char EMPTYCHAR = ' ';
            const string EMPTYSTRING = " ";

            /// <summary>
            /// Reverse a string Sentence
            /// </summary>
            /// <param name="pStr"></param>
            /// <returns></returns>
            public string ReverseString(string pStr)
            {
                string strReversed = String.Empty;
                string[] strSplitted = new String[pStr.Length];
                int i;

                strSplitted = Split(pStr); // Complexity till here O(n)

                for (i = strSplitted.Length - 1; i >= 0; i--)  // this for loop add O(length of string) in O(n) which is similar to O(n)
                {
                    strReversed += strSplitted[i];

                }

                return strReversed;

            }

            /// <summary>
            /// Split the string into words & empty spaces
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public string[] Split(string str)
            {
                string strTemp = string.Empty;
                string[] strArryWithValues = new String[str.Length];
                int j = 0;
                int countSpace = 0;

                //Complexity of for conditions result to O(n)
                foreach (char ch in str)
                {
                    if (!ch.Equals(EMPTYCHAR))
                    {
                        strTemp += ch; //append characters to strTemp

                        if (countSpace > 0)
                        {
                            strArryWithValues[j] = ReturnSpace(countSpace); // Insert String with Spaces
                            j++;
                            countSpace = 0;
                        }
                    }
                    else
                    {
                        countSpace++;

                        if (countSpace == 1)
                        {
                            strArryWithValues[j] = strTemp; // Insert String with Words
                            strTemp = String.Empty;
                            j++;
                        }
                    }

                }

                strArryWithValues[j] = strTemp;

                return (strArryWithValues);

            }

            /// <summary>
            /// Return a string with number of spaces(passed as argument)
            /// </summary>
            /// <param name="count"></param>
            /// <returns></returns>
            public string ReturnSpace(int count)
            {
                string strSpaces = String.Empty;

                while (count > 0)
                {
                    strSpaces += EMPTYSTRING;
                    count--;
                }

                return strSpaces;

            }


            /************Reverse Sentence Ends***************/

    Wednesday, January 02, 2013 7:49 PM
  • I think this may be more of what you are looking for.  Basically its a simple C++ programming interview question.  Replace a string in place.  For C# I believe you have to use StringBuilder instead of string since strings are immutable and don't like to be changed like that.

            static void Reverse(ref StringBuilder str, int startIndex, int endIndex)
            {
                while (startIndex < endIndex)
                {
                    char t = str[startIndex];
                    str[startIndex++] = str[endIndex];
                    str[endIndex--] = t;
                }
            }

            static void Main(string[] args)
            {
                StringBuilder str = new StringBuilder("String To Reverse");
                Reverse(ref str, 0, str.Length-1);

                int wordStartIndex = 0;
                for(int j = 0; j < str.Length; j++)
                {
                    if (str[j] == ' ')
                    {
                        Reverse(ref str, wordStartIndex, j-1);
                        wordStartIndex = ++j; // increment past the ' '
                    }
                }
                Reverse(ref str, i, str.Length-1);  // reverse the last word in the string
            }

    Friday, April 05, 2013 6:23 AM
  • Marvelous solution
    Monday, June 24, 2013 4:30 PM