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 :
ReverseString( String )
: returns reversed string, e.g., ReverseString("Hello How are you")
.Split( String )
: returns a string array containing words and spaces at consecutive places.ReturnSpace( int )
: accepts an integer representing number of spaces, creates and return a string containing specified number of spaces.
const char EMPTYCHAR = ' ';
const string EMPTYSTRING = " ";
public string ReverseString(string pStr)
{
if (pStr.Length > 1)
{
string strReversed = String.Empty;
string[] strSplitted = new String[pStr.Length];
int i;
strSplitted = Split(pStr);
for (i = strSplitted.Length - 1; i >= 0; i--)
{
strReversed += strSplitted[i];
}
return strReversed;
}
return pStr;
}
public string[] Split(string str)
{
string strTemp = string.Empty;
string[] strArryWithValues = new String[str.Length];
int j = 0;
int countSpace = 0;
foreach (char ch in str)
{
if (!ch.Equals(EMPTYCHAR))
{
strTemp += ch;
if (countSpace > 0)
{
strArryWithValues[j] = ReturnSpace(countSpace);
j++;
countSpace = 0;
}
}
else
{
countSpace++;
if (countSpace == 1)
{
strArryWithValues[j] = strTemp;
strTemp = String.Empty;
j++;
}
}
}
strArryWithValues[j] = strTemp;
return (strArryWithValues);
}
public string ReturnSpace(int count)
{
string strSpaces = String.Empty;
while (count > 0)
{
strSpaces += EMPTYSTRING;
count--;
}
return strSpaces;
}
Similar post
Points of Interest
Maintaining complexity to O(n) where n is length of string.