Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Reverse a string

string

  • Please log in to reply
6 replies to this topic

#1 Termana

Termana

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 971 posts

Posted 30 November 2008 - 05:37 AM

In C#, there is no in-built reverse string algorithm (that I know of anyhow), so you need to build your own function to do so.

1. Start a new project (File -> New Project -> Console Application -> OK)
2. In the main function we are going to just read a line and call our reverse function to print it to the screen, so we'll use this code:

        static void Main(string[] args)
        {
            string readline;
            readline = ReverseString(Console.ReadLine());
            Console.WriteLine(readline);
        }

3. Now we need to put in the ReverseString function. Under the Main function ending curly brace put this code in:

        static string ReverseString(string str)
        {
            string newstr = "";
            for (int i = 1; i < str.Length; i++)
            {
                newstr = newstr + str[str.Length - i];
            }
            newstr = newstr + str[0];
            return newstr;
        }

This is a simple algorithm I designed to reverse the string.

4. Run the program (Press Ctrl+F5) and type in a line and press enter. It will print the string back to you! Now you can use the ReverseString function anywhere, and you dont just have to use it for this purpose!

Hope this helps you reverse string :)

*Note: There are better ways to reverse the string, but this just came off the top of my head and works.
  • 2

Interested in participating in community events?
Want to harness your programming skill and turn it into absolute prowess?
Come join our programming events!


#2 amrosama

amrosama

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 2765 posts

Posted 30 November 2008 - 11:18 AM

good tutorial!
+rep, keep posting tutorials
  • 0
yo homie i heard you like one-line codes so i put a one line code that evals a decrypted one line code that prints "i love one line codes"
eval(base64_decode("cHJpbnQgJ2kgbG92ZSBvbmUtbGluZSBjb2Rlcyc7"));
www.amrosama.com | the unholy methods of javascript

#3 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 30 November 2008 - 12:34 PM

Well done, quite useful.

Another way to reverse a string:

static string reverse(string s)
        {
            if (s.Length <= 1)
            {
                return s;
            }
            else
            {
                return reverse(s.Substring(1))+s[0];
            }
        }

  • 0

#4 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 30 November 2008 - 12:53 PM

Your Main() function is this:

static void Main(string[] args)
        {
            string readline;
            readline = ReverseString(Console.ReadLine());
            Console.WriteLine(readline);
        }

Why not just do this:

Console.WriteLine(ReverseString(Console.ReadLine()));

It saves on having to create a variable to store the reversed string.

Another performance measure you have not thought of:

newstr = newstr + str[str.Length - i];

And again here:

newstr = newstr + str[0];

String concatenation is inefficient. .NET cannot concatenate strings directly - instead it must create a new string variable containing both the old values, then discards the old two variables. If you are doing this for every single character, it is going to slow performance of your program.

Use a StringBuilder instead, and call its Append() method, passing a string parameter, to concatenate text. When you are done, call ToString() to return the string value held by the StringBuilder.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#5 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 30 November 2008 - 01:05 PM

Is my recursive method doing the same thing with the concatenation?
  • 0

#6 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 30 November 2008 - 01:23 PM

Your code:

static string reverse(string s)
        {
            if (s.Length <= 1)
            {
                return s;
            }
            else
            {
                return reverse(s.Substring(1))+s[0];
            }
        }

How about this code:

static string reverse(string s)
  {
    return s.Length <= 1 ? s : reverse(s.Substring(1))+s[0];
  }

It uses the conditional operator and hence is much more concise.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#7 Barnsite

Barnsite

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 258 posts
  • Location:West Sussex, UK
  • Programming Language:C#, (Visual) Basic, Visual Basic .NET, Transact-SQL, Others
  • Learning:Java

Posted 25 October 2012 - 04:03 AM

Another way is to use Array.Reverse

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

  • 0
There are two ways to write error-free programs; only the third one works.





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download