In C# development, working with strings and characters is essential. This article explores how to convert a string to a char array. It also extends into converting arrays of strings to arrays of characters.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Converting a Single Character String to Char

If we have a single character string, we can convert the string to a char:

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
public static char ConvertSingleCharacterStringToChar(string inputString)
{
    return char.Parse(inputString);
}

Here, our method makes use of the char.Parse(). It takes a string as input and returns its first character if the string has exactly one character. Note, that char.Parse() will throw an exception if the input string’s length is greater than 1.

Converting a String to a Char Array

Let’s look at an example to show how to accomplish the conversion of a string with more than one character to a char array using a straightforward method:

public static char[] ConvertStringToCharArray(string inputString)
{
    return inputString.ToCharArray();
}

The ConvertStringToCharArray() method takes a string input and then makes use of the ToCharArray() method to convert the input string into a character array. The ToCharArray() method returns a new array containing the characters of the string.

Let’s test it out:

string myString = "Hello World!";
char[] charArray = StringHelper.ConvertStringToCharArray(myString);

We call the method passing a string to it, and it returns a character array containing the individual characters of the string. The result, charArray, can then be used for further processing or manipulation as needed.

This method is a convenient way to convert a string to a character array, and it leverages the built-in functionality provided by the string class in C#.

Using ReadOnlySpan as an Alternative to Char

ReadOnlySpan<T> is a type in C# that provides a read-only view over a block of memory, without creating a new array or copying data. It’s particularly useful when dealing with performance-critical scenarios or when we want to work with data without the overhead of array creation.

To learn more about the ReadOnlySpan type, check out our article here.

In the context of character data, ReadOnlySpan<char> can be considered an alternative to char[] when we need to work with a sequence of characters without modifying the underlying data.

Let’s see how we can achieve this:

public static ReadOnlySpan<char> ConvertStringToCharArrayUsingReadOnlySpan(string inputString)
{
    return inputString.AsSpan();
}

The ConvertStringToCharArrayUsingReadOnlySpan() method converts a string to a read-only span of characters. It utilizes the AsSpan() method to create a read-only view of the characters in the input string. The resulting ReadOnlySpan<char> allows for efficient and read-only access to the underlying character data of the string without allocating a new array.

Now, we call the method:

ReadOnlySpan<char> charArrayReadOnlySpan = StringHelper.ConvertStringToCharArrayUsingReadOnlySpan(myString);

Comparison of ToCharArray and AsSpan

  • ToCharArray() creates a new char[] on the heap, while AsSpan() simply creates a ReadOnlySpan<char> view over the existing data
  • The resulting char[] is mutable meaning we can modify the contents of the array, whileReadOnlySpan<char> is read-only so we cannot
  • ToCharArray() involves both memory allocation and copying, while AsSpan() is generally more performant as it requires no allocation or copying

Converting String Array to Char Array Using Loop

Now, let’s take it a step further and explore the conversion of an array of strings to an array of characters.

Let’s see how to accomplish this with the help of StringBuilder:

public static char[] ConvertStringArrayToCharArrayUsingLoop(string[] stringArray)
{
    var combinedString = new StringBuilder();

    foreach (var str in stringArray)
    {
        combinedString.Append(str);
    }

    var result = new char[combinedString.Length];
    combinedString.CopyTo(0, result, 0, result.Length);

    return result;
}

Here, we first create a StringBuilder and concatenate the strings together using the Append() method. Next, we allocate a result char array based on the length of the concatenated string. Finally, we copy the contents of the combinedString into our result array and return it. Note that we don’t add a separator when concatenating the elements of the stringArray.

Converting String Array to Char Array Using LINQ

We can also achieve the same result using LINQ instead of a loop:

public static char[] ConvertStringArrayToCharArrayUsingLinq(string[] stringArray)
{
    return stringArray.SelectMany(s => s.ToCharArray()).ToArray();
}

This ConvertStringArrayToCharArrayUsingLinq() method converts an array of strings, stringArray, into a single-character array char[] using LINQ (Language Integrated Query).

For more details on LINQ, please check out our article on LINQ.

Here we use LINQ’s SelectMany() to transform each string in the array into a sequence of characters. The ToCharArray() method is applied to each string, resulting in a sequence of characters. Finally, ToArray() converts the sequence into a single char[].

This method performs the concatenation of characters from all strings in the collection into a single char[]. It’s a concise and readable way to achieve the desired result using LINQ’s expressive syntax.

Conclusion

In this article, we’ve learned how to convert a string to a char array. We also went a step forward, converting an array of strings into a char array. Understanding how to convert strings to character arrays and extending it to handle arrays of strings provides valuable flexibility in C# programming. Whether working with individual strings or collections of strings, these conversions are powerful tools in our development toolkit.

By leveraging these techniques, we can enhance the efficiency and versatility of our C# applications when dealing with string and character manipulations.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!