Converting from String to Char or Visa Versa

Posted Mon, Feb 22 2010 13:18 by Deborah Kurata

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!

Filed under: , , ,

Comments

# Linked - List

Tuesday, February 23, 2010 1:35 PM by ASeventhSign

Linked - List

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: