Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] Reversing a string

Started by tasen Mar 14, 2007 at 7:01 PM 4 replies 1.5k views
Original Post
tasen
tasen
Hi all, I've just spent the last half hour Googling for an answer to this but I can't seem to find one; is there a method for reversing strings in C#? All the sites seem to be rolling their own methods to do it. Am I missing something obvious here or should I just roll my own method as well?
string str = "Hello";

Reverse(string); // i.e. str == "olleH"
Any help is greatly appreciated.
intransigent-seal
intransigent-seal
The Array class contains a method for reversal, but to use it you'd have to convert the string to a char array and back, something like:
{    string s = "Hello, world!";    char[] cs = s.ToCharArray();    Array.Reverse(cs);    string reversed = new String(cs);}
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
Xai
Xai
and the reason people roll there own, is they can do it with 1 less copy than the "built-in" method ... or cause they just never thought of using the array reverse.
tasen
tasen
Quote:
Original post by JohnBSmall
The Array class contains a method for reversal, but to use it you'd have to convert the string to a char array and back, something like:
*** Source Snippet Removed ***


Thanks. That's what I was looking for (and indeed, for the stuff I'm doing a char array is more appropriate anyway).

Also, on an unrelated note, is there a built-in function to output arrays with (i.e. a character array), or must I just loop through the array manually and print each character?

Cheers
benryves
benryves
There is a constructor for string that takes an array of char (as demonstrated in JohnBSmall's post); that is you could do:

char[] SomeCharArray;
Console.WriteLine(new string(SomeCharArray));
[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]
intransigent-seal
intransigent-seal
The output functions (eg, Console.WriteLine) have an overload that takes a char[] array directly, so you don't even have to create the string object.

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.