Click here to Skip to main content
Click here to Skip to main content

How to reverse a string sentence (only words, not characters) without using the C# "string built-in" functions

By , 5 Jan 2013
 

Introduction

This article represents one of few ways of reversal of string sentence (only words, without using any inbuilt c# functions except String.Length property as author feels lazy to write code for it.)

Background

Knowledge of control structures (for, foreach, while) and data types (char, string).

Using the code

There are mainly three functions created :

  1. ReverseString( String ): returns reversed string, e.g., ReverseString("Hello How are you").
  2. Split( String ): returns a string array containing words and spaces at consecutive places.
  3. ReturnSpace( int ): accepts an integer representing number of spaces, creates and return a string containing specified number of spaces.
/**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)
{
  if (pStr.Length > 1) //can be checked/restricted via validation
  {
    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;
  }
  return pStr;
}

/// <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***************/

Similar post

Points of Interest

Maintaining complexity to O(n) where n is length of string.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

VeeQuest
Software Developer
United States United States
Member
Learning & Earning.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionAnother suggestionmemberMalte Klena9 Jan '13 - 7:08 
To my mind, your solution is to complicated.
I would do it this way (in VB):
 
Public Function ReverseString(input As String) As String
    Dim sb As New StringBuilder
 
    Dim mt As RegularExpressions.Match = _
        RegularExpressions.Regex.Match(input, "(\b[^\s]+\b)|([\s]+)", _
                                       RegularExpressions.RegexOptions.RightToLeft Or _
                                       RegularExpressions.RegexOptions.Compiled)
 
    While Not mt Is Nothing AndAlso mt.Success
        sb.Append(mt.Value)
        mt = mt.NextMatch
    End While
 
    Return sb.ToString
End Function
 
But of course I do not mind using build in functions...
SuggestionHow about this...memberAndreas Gieriet5 Jan '13 - 12:11 
Quick and dirty Wink | ;-)
public static string ReverseWordSequencePreservingSpaces(string input)
{
    // collect the result in a character array first
    char[] output = new char[input.Length];
    // iterate over input from back to front, buffering non-space characters, and flushing the buffer to the output with each word gap (space)
    int buflen = 0;
    int outpos = 0;
    int inpos = input.Length;
    while(inpos-- > 0)
    {
        char c = input[inpos];
        if (c == ' ')
        {
            // flush the buffer to the output
            if (buflen > 0) for (int pos = inpos + 1; buflen-- > 0; ++pos) output[outpos++] = input[pos];
            // append the space
            output[outpos++] = c;
        }
        else
        {
            // push non space to the buffer, i.e. count the number of non-space characters
            buflen++;
        }
    }
    // final flush of the buffer
    for (int pos = inpos + 1; buflen-- > 0; ++pos) output[outpos++] = input[pos];
    // return string from array
    return new string(output);
}
 
Cheers
Andi
 
PS: I would not suggest to do this in productive code, though - I regard it as mental training only Wink | ;-)
QuestionRepeatmemberjfriedman4 Jan '13 - 4:15 
See Various string reversal algorithms in C#[^]
 
Besides splitting the string to reverse it is wasteful, you could achieve the same without split.
AnswerRe: RepeatmemberPIEBALDconsult4 Jan '13 - 4:35 
But he wants to reverse the "words"; not the characters.
GeneralRe: Repeatmemberjfriedman4 Jan '13 - 5:21 
Still don't need to split Smile | :)
 
int p =  s.IndexOf(' ', 0);
 while(p != -1 && p < s.Length) { 
 /*Do something with your substring*/ 
 //Get the next index
 p =  s.IndexOf(' ', ++p ); 
}

GeneralRe: RepeatmemberPIEBALDconsult4 Jan '13 - 10:51 
I'm fairly sure it's not a real-world requirement anyway. Roll eyes | :rolleyes:
GeneralRe: RepeatmemberVeeQuest5 Jan '13 - 9:24 
Absolutely, its not Smile | :) ,but a question just can't be left unanswered. I will look forward for more interesting solutions for this like given by @maq_rohit
SuggestionUse StringBuildersmemberJohn Brett2 Jan '13 - 22:06 
String concatenation in managed languages is notoriously memory-inefficient.
If you're going to use these methods on any significant pieces of text, you ought to be using the StringBuilder class to concatenate results.
 
John
GeneralRe: Use StringBuildersmemberadriancs3 Jan '13 - 7:46 
Agree
GeneralThoughtsmemberPIEBALDconsult2 Jan '13 - 16:38 
Why not just use an appropriate constructor for string, I don't think it would violate the spirit of "not using built-in functions". Bear in mind that even the += operator is actually just shorthand for a "built-in function" anyway.
QuestionGood onemembermaq_rohit2 Jan '13 - 14:53 
This is good approach but its could be more simple if we reverse string and after that one more pass for reverse character And worst case complexity is O(n)
static char[] ReverseAllWords(char[] in_text)
    {
        int lindex = 0;
        int rindex = in_text.Length - 1;
        if (rindex > 1)
        {
            //reverse complete phrase
            in_text = ReverseString(in_text, 0, rindex);
 
            //reverse each word in resultant reversed phrase
            for (rindex = 0; rindex <= in_text.Length; rindex++)
            {
                if (rindex == in_text.Length || in_text[rindex] == ' ')
                {
                    in_text = ReverseString(in_text, lindex, rindex - 1);
                    lindex = rindex + 1;
                }
            }
        }
        return in_text;
    }
 
    static char[] ReverseString(char[] intext, int lindex, int rindex)
    {
        char tempc;
        while (lindex < rindex)
        {
            tempc = intext[lindex];
            intext[lindex++] = intext[rindex];
            intext[rindex--] = tempc;
        }
        return intext;
    }

AnswerRe: Good onememberVeeQuest5 Jan '13 - 9:26 
Thumbs Up | :thumbsup:
GeneralRe: Good onemembermaq_rohit9 Jan '13 - 19:28 
Improved it more and made it in single loop
 
public static string ReverseString(string strInput)
       {
           string strWord = String.Empty;
           string strResult = String.Empty;
           for (int i = strInput.Length - 1; i >= 0; i--)
           {
               if (strInput[i].ToString() != " ")
                   strWord = strInput[i] + strWord;
               else
               {
                   strResult = strResult + " " + strWord;
                   strWord = "";
               }
           }
           strResult = strResult + " " + strWord;
 
           return strResult;
       }

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 5 Jan 2013
Article Copyright 2013 by VeeQuest
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid