简体   繁体   中英

How to convert char[] to char?

I am new to C#. I am trying to declare a char array that contains few string values. Trying to use the ToCharArray() method to copy the string to a char array it return character array of a string. However, I get the error saying it cannot implicitly convert char[] to char .

Here's the code I have written:

char[] country= new char[5];
country[1] = "japan".ToCharArray();
country[2] = "korea".ToCharArray();

It works when I write it like this:

char[] country= "japan".ToCharArray();

but I want to use it in an array so I can randomize and choose an element from any of 5 values assigned. I would really appreciate if anyone could help, thanks.

I believe you try to have array of char arrays:

char[][] countries = new char[5][];
countries[1] = "japan".ToCharArray();
countries[2] = "korea".ToCharArray();

Every element in the array is one character. So country[0] is "j", country[1] is "a" and so on.

with

country[1] = "japan".ToCharArray();

you try to put an array into a char, and give you an error. Perhaps you want a list of chars. So you can use an array of array or a list of country. for the first country for example

List<string> country = new List<string>() {
    "japan",
    "korea"
};

var random = new Random();
var character = country[0][random.Next(0, country[0].Length)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM