user300484
user300484

Reputation: 493

C# simple error: Storing characters in a string array

I want to store every single character of a string value in every single place of a string array.

I wrote this code but Visual Studio says that "Cannot implicitly convert type String to String []".

Can you please tell me how to fix this?

string [] array = Console.ReadLine();

Upvotes: 0

Views: 740

Answers (4)

Jeffrey L Whitledge
Jeffrey L Whitledge

Reputation: 59463

The answer depends on your definition of "character". If you are talking about code points (i.e., chars) then there are several answers given. If you are talking about linguistic characters, then here is a way to do it:

        string[] array = GetAllCharacters(Console.ReadLine()).ToArray();

Using this method:

using System.Globalization;
...
    private static IEnumerable<string> GetAllCharacters(string text)
    {
        TextElementEnumerator elementEnumerator = StringInfo.GetTextElementEnumerator(text);
        while (elementEnumerator.MoveNext())
            yield return (string)elementEnumerator.Current;
    }

Upvotes: 0

pierroz
pierroz

Reputation: 7870

Console.ReadLine() returns a string. Then if you really need a char array, you can use string.ToCharArray()

Upvotes: 0

Etienne de Martel
Etienne de Martel

Reputation: 36852

You can get an array of characters (char[]) with the ToCharArray() method of String. You can then use LINQ or something to convert each individual char to a string.

Very weird request though.

Upvotes: 1

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

Console.ReadLine does not return an array but a string:

string line = Console.ReadLine();

In your code, the variable array is declared as a string array, so the result of Console.ReadLine cannot be assigned to it.

Upvotes: 6

Related Questions