Click here to Skip to main content
15,867,453 members
Articles / Desktop Programming / Win32

How to reverese a string in C#/.NET with almost one line of code using P/Invoke

Rate me:
Please Sign up or sign in to vote.
2.67/5 (8 votes)
4 Jan 2013CPOL3 min read 49.5K   92   4   41
How to reverese a string in C#/.NET with almost one line of code using a build in Windows library function which is available on any Windows system.

Introduction 

This short article shows how to use an exported function from the Microsoft Visual C Run-Time Library wich is almost available on any Windows System starting Windows 95 to the latest Windows 8 to reverse a string in C# within a single line of code.

Background 

At times we need to reverese a string in .NET for particular reasons. In general developers code their own functions and classes holding some sort of class/function pair to accomplish this task, unless there is no ready to use code or external library/assembly available. But the implementation itself can heavily differ in code quality, speed and size, depending on the developers skills and generated code by the compiler. Keep in your mind, that there are many more compilers beside the broadly used Microsoft compilers, who can generate IL code and they can differ in optimization and other variables which finally can affect the applications performance. By using the Microsoft Visual C Run-Time Library functions _strrev() and/or _wcsrev() we can quickly reverse a string within a single line of code. These functions can easily be imported and used by a .NET project using the .NET Framework's Interop techniques. CodeProject has a lot of great articles on the Interop topic, so there is no need to explain what .NET Interop in detail is. By using these two Microsoft supplied functions, there are some major advantages over external third-party libraries: 

  • The Microsoft Visual C Run-Time Library is available without exception on any Windows system starting from Windows 95 to the latest Windows 8, covering the 32- and 64 bit variants. The library itself is de-facto an integral part of the Windows system and many Windows applications itself depend on its existence to work properly.
  • The functions are very well documented and very stable, so they can be safely used in any project without exceptions. Beside the fact that there are different version available and possibly installed on a system, the input and output data is ALWAYS the same on any library version.
  • The library code is maintained by Microsoft and any bugfixes will be available on any Windows systems with new or update releases of the Microsoft Visual C Run-Time Library.
  • The code runs pretty fast. Fast means here that the implementation code, the code inside the library, is written in plain C and the only thing to marshal between the library and the managed application is the string (in fact the string pointer) itself. This can make the reversing operation on even large strings very fast.

Using the code   

Using the code is pretty straightforward and the C# signatures can easily be imported to any .NET language like e.g. VB.NET by simply translating them into their language counterparts. The project files hold a simple C# Visual Studio 2008 file format Forms expample project that shows you a simple application with basic commented code on how to use these two functions. Lets have a look at the code now:

The very first thing we have to do is to import the System.Runtime.InteropServices namespace into our project in order to be able to use the Interop mechanism and use the two functions in our project:

C#
using System.Runtime.InteropServices;      

Now we can declare our import functions signatures inside a class in our project. They have to look like this:

C#
/*  Original documentation for _strrev, _wcsrev, _mbsrev, _mbsrev_l 
 *  on the Micdrosoft MSDN Libary pages: 
 *  http://msdn.microsoft.com/en-us/library/9hby7w40%28v=vs.80%29.aspx
 */

// UNICODE variant
[DllImport("msvcrt.dll",
    CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string _wcsrev(
    [MarshalAs(UnmanagedType.LPWStr)]
    [In] string str);

// ANSI variant
[DllImport("msvcrt.dll",
    CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string _strrev(
    [MarshalAs(UnmanagedType.LPStr)]
    [In] string str);

That's it! Now they can be used like any C# function within your code: Here is a short example to show you how:

C#
public partial class Form1 : Form
{
    /*  Original documentation for _strrev, _wcsrev, _mbsrev, _mbsrev_l 
     *  on the Micdrosoft MSDN Libary pages: 
     *  http://msdn.microsoft.com/en-us/library/9hby7w40%28v=vs.80%29.aspx
     */

    // UNICODE variant
    [DllImport("msvcrt.dll",
        CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.LPWStr)]
    public static extern string _wcsrev(
        [MarshalAs(UnmanagedType.LPWStr)]
        [In] string str);

    // ANSI variant
    [DllImport("msvcrt.dll",
        CharSet = CharSet.Ansi)]
    [return: MarshalAs(UnmanagedType.LPStr)]
    public static extern string _strrev(
        [MarshalAs(UnmanagedType.LPStr)]
        [In] string str);
 
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        // make sure you pass in a valid string
        // passing a null will lead to a System.AccessViolationException exception
        if (string.IsNullOrEmpty(this.textBox1.Text.Trim()) == true)
        {
            MessageBox.Show("The original string cant be empty. Please set the original text first!",
                this.Text,
                MessageBoxButtons.OK,
                MessageBoxIcon.Exclamation);

            return;
        }

        try
        {
            //we are using the UNICODE variant, since all strings in .NET are UNICODE by default
            this.textBox2.Text = _wcsrev(textBox1.Text);
        }
        catch (Exception err)
        {
            MessageBox.Show("Error reversing string: " + err.Message,
                this.Text,
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }
}

Important to know

Please make sure that you pass in a valid string as the functions parameter and not a null. Passing in something like "" or a string.Empty (both are the same at runtime) is perfectly fine, but passing in a null as parameter will definitely lead to a System.AccessViolationException kind of exception and crash your application if you dont handle the exception inside a try/catch block.

History 

  • 03/01/13 - Initial release
  • 04/01/13 - Changed topic text to make it more fit the approach technique

External links  

Original documentation for _strrev, _wcsrev, _mbsrev, _mbsrev_l:
http://msdn.microsoft.com/en-us/library/9hby7w40%28v=vs.80%29.aspx.

License

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


Written By
Software Developer (Senior)
Germany Germany
I am a former developer from germany who has worked on a broad range of technologies. Mainly i was assigned to tasks like designing, writing and implementing/integrating applications for mixed systems, debugging and troubleshooting them, also including lots of teaching on how to do all those things. I was not tied to any special systems at all, as long it could be programmed somehow, no matter in kernel or userland Smile | :) Currently i am not developing or teaching anymore. But i still try to help and contribute code and solutions, help wherever i can. I am also strongly interessted in pedagogy, especially in media pedagogy. There are a few final words i want to say here: Share your knowledge of programming, of life and all your experiences to anybody out there, to build a better and safer world. We only have one. Please try to keep it safe for all of us.

Comments and Discussions

 
GeneralMy vote of 5 Pin
fredatcodeproject19-Dec-13 4:22
professionalfredatcodeproject19-Dec-13 4:22 
SuggestionAfter all, I vote for Microsoft.VisualBasic.Strings.StrReverse(...) Pin
Andreas Gieriet5-Jan-13 11:16
professionalAndreas Gieriet5-Jan-13 11:16 
SuggestionOther way Pin
Thomas Daniels4-Jan-13 23:42
mentorThomas Daniels4-Jan-13 23:42 
GeneralRe: Other way Pin
Andreas Gieriet5-Jan-13 11:19
professionalAndreas Gieriet5-Jan-13 11:19 
GeneralRe: Other way Pin
alex_zero6-Jul-15 17:08
alex_zero6-Jul-15 17:08 
GeneralMy vote of 1 Pin
abdurahman ibn hattab4-Jan-13 8:29
abdurahman ibn hattab4-Jan-13 8:29 
GeneralRe: My vote of 1 Pin
Kerem Guemruekcue4-Jan-13 19:29
Kerem Guemruekcue4-Jan-13 19:29 
GeneralMy vote of 2 Pin
Akinmade Bond4-Jan-13 5:34
professionalAkinmade Bond4-Jan-13 5:34 
GeneralRe: My vote of 2 Pin
Kerem Guemruekcue4-Jan-13 6:10
Kerem Guemruekcue4-Jan-13 6:10 
QuestionInterop is a little heavy Pin
jfriedman4-Jan-13 4:18
jfriedman4-Jan-13 4:18 
AnswerRe: Interop is a little heavy Pin
Kerem Guemruekcue4-Jan-13 4:48
Kerem Guemruekcue4-Jan-13 4:48 
GeneralRe: Interop is a little heavy Pin
jfriedman4-Jan-13 5:15
jfriedman4-Jan-13 5:15 
GeneralRe: Interop is a little heavy Pin
Kerem Guemruekcue4-Jan-13 5:30
Kerem Guemruekcue4-Jan-13 5:30 
GeneralMy vote of 2 Pin
Jon Larborn4-Jan-13 2:08
Jon Larborn4-Jan-13 2:08 
GeneralRe: My vote of 2 Pin
Kerem Guemruekcue4-Jan-13 2:45
Kerem Guemruekcue4-Jan-13 2:45 
GeneralMy vote of 1 Pin
RogerDW4-Jan-13 1:06
RogerDW4-Jan-13 1:06 
GeneralRe: My vote of 1 Pin
Kerem Guemruekcue4-Jan-13 1:17
Kerem Guemruekcue4-Jan-13 1:17 
GeneralMy vote of 1 Pin
Krzysztof Kalinowski3-Jan-13 23:58
Krzysztof Kalinowski3-Jan-13 23:58 
GeneralRe: My vote of 1 Pin
Kerem Guemruekcue4-Jan-13 0:35
Kerem Guemruekcue4-Jan-13 0:35 
GeneralMy vote of 3 Pin
Andreas Gieriet3-Jan-13 22:00
professionalAndreas Gieriet3-Jan-13 22:00 
GeneralRe: My vote of 3 Pin
Kerem Guemruekcue4-Jan-13 0:28
Kerem Guemruekcue4-Jan-13 0:28 
Hi Andi,

i wasnt sure about the topic, but after reading your comment, it should be a better one, you are right. Its not that overkill, its just one import directive, a signature declaration and the final call. Strictly spoken its three lines if you count the using and declaration, the effective is one single line. John Andersons suggestion is fine, but has a major limitation over my approach. Please read my comment on his post for more information if you like.

best

K.

-----------------------
Beste Grüsse / Best regards / Votre bien devoue
Kerem Gümrükcü
-----------------------
"This reply is provided as is, without warranty express or implied."
GeneralRe: My vote of 3 Pin
Andreas Gieriet4-Jan-13 1:08
professionalAndreas Gieriet4-Jan-13 1:08 
GeneralRe: My vote of 3 Pin
Kerem Guemruekcue4-Jan-13 1:29
Kerem Guemruekcue4-Jan-13 1:29 
GeneralRe: My vote of 3 Pin
Andreas Gieriet4-Jan-13 1:44
professionalAndreas Gieriet4-Jan-13 1:44 
GeneralRe: My vote of 3 Pin
Kerem Guemruekcue4-Jan-13 2:42
Kerem Guemruekcue4-Jan-13 2:42 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.