Split String in C# without delimiter (sort of)

前端 未结 2 1031
无人及你
无人及你 2020-12-11 03:06

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

相关标签:
2条回答
  • 2020-12-11 03:55

    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();
    
    0 讨论(0)
  • 2020-12-11 04:02

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

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

    0 讨论(0)
提交回复
热议问题