C# - How to convert string to char?

余生颓废 提交于 2020-04-12 08:18:09

问题


I am a beginner in C# and I would like to know how to convert strings to chars, specifically string[] to char[]. I tried ToCharArray(), but I then I got an error saying that it doesn't exist. Convert.ToChar(<char here>) gives me a error saying

cannot convert from "char" to "System.Array"


回答1:


Use:

string str = "Hello";
char[] characters = str.ToCharArray();

If you have a single character string, You can also try

string str = "A";
char character = char.Parse(str);    

//OR 
string str = "A";
char character = str.ToCharArray()[0];



回答2:


A string can be converted to an array of characters by calling the ToCharArray string's method.

var characters = stringValue.ToCharArray();

An object of type string[] is not a string, but an array of strings. You cannot convert an array of strings to an array of characters by just calling a method like ToCharArray. To be more correct there isn't any method in the .NET framework that does this thing. You could however declare an extension method to do this, but this is another discussion.

If your intention is to build an array of the characters that make up the strings you have in your array, you could do so by calling the ToCharArray method on each string of your array.




回答3:


string[] arrayStrings = { "One", "Two", "Three" };
var charArrayList = arrayStrings.Select(str => str.ToCharArray()).ToList();



回答4:


char[] myChar = theString.ToCharArray();



回答5:


string[] array = {"USA", "ITLY"};
char[] element1 = array[0].ToCharArray();
// Now for element no 2
char[] element2 = array[1].ToCharArray();



回答6:


Your question is a bit unclear, but I think you want (requires using System.Linq;):

var result = yourArrayOfStrings.SelectMany(s => s).ToArray();

Another solution is:

var result = string.Concat(yourArrayOfStrings).ToCharArray();


来源:https://stackoverflow.com/questions/33946594/c-sharp-how-to-convert-string-to-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!