Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String in C# without delimiter (sort of)

I want to split a string in C#.NET that looks like this:

string Letters = "hello";

and put each letter (h, e, l, l, o) into an array or ArrayList. I have no idea what to use as the delimiter in String.Split(delimiter). I can do it if the original string has commas (or anything else):

string Letters = "H,e,l,l,o";
string[] AllLettersArray = Letters.Split(",".ToCharArray());

But I have no idea what to use in a case with (supposedly) no delimiter. Is there a special character like Environment.Newline? Thanks.

like image 285
Zach S Avatar asked Sep 28 '09 03:09

Zach S


2 Answers

Remember, you can access a string as an array in c#.

string str = "hello";
char[] letters = str.ToCharArray();

like image 133
Justin Cherniak Avatar answered Nov 08 '22 05:11

Justin Cherniak


Here is another full solution that uses a loop. This takes a regular string "helloworld" and puts each character into an array as a string. The most straightforward method without using LINQ or other references.

string str = "helloworld";
string[] arr = new string[str.Length];

for(int i=0; i<str.Length; i++)
{
    arr[i] = str[i].ToString();
}

This can be added to your codebase as an extension method.

public static class StringExtensions
{
    public static string[] ToStringArray(this string str)
    {
        string[] arr = new string[str.Length];

        for(int i=0; i<str.Length; i++)
        {
            arr[i] = str[i].ToString();
        }

        return arr;
    }
}

And then you have a 1 liner for the conversion.

string str = "helloworld";
string[] arr = str.ToStringArray();
like image 1
GER Avatar answered Nov 08 '22 05:11

GER