Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

February 22, 2010

Converting from String to Char or Visa Versa

Filed under: C#,VB.NET @ 3:18 pm

When working with Char values, you may need to convert an existing string to an array of chars, or you may want to convert an array of chars back into a single string.

Converting a String to an Array of Char

The following code converts a string to an array of Char.

In C#:

string myName = "Deborah";
char[] myNameChars = myName.ToCharArray();

foreach (char c in myNameChars)
{
    Console.WriteLine(c);
}

In VB:

Dim myName = "Deborah"
Dim myNameChars As Char() = myName.ToCharArray()

For Each c As Char In myNameChars
    Console.WriteLine(c)
Next

The ToCharArray method of the string provides the string as an array of char values.

Converting a Char Array to a String

There are times you need to do the opposite as well. Say you want to work with a set of characters in an array, but then you want to append the characters back into a string.

In C#:

// Reverse the array
myNameChars = myNameChars.Reverse().ToArray();
string myNameBackwards = new string(myNameChars);
Console.WriteLine(myNameBackwards);

In VB:

‘ Reverse the array
myNameChars = myNameChars.Reverse().ToArray()
Dim myNameBackwards = New String(myNameChars)
Console.WriteLine(myNameBackwards)

The result is: harobeD.

The above code leverages one of the String overloads that takes a char array as a parameter.

Use these techniques any time you need to convert between a string and a char array.

Enjoy!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs