C#简单错误:将字符存储在字符串数组中
我想在字符串数组的每个位置存储字符串值的每个字符 我写了这段代码,但VisualStudio说“不能隐式地将类型字符串转换为字符串[]” 你能告诉我怎么修理这个吗C#简单错误:将字符存储在字符串数组中,c#,C#,我想在字符串数组的每个位置存储字符串值的每个字符 我写了这段代码,但VisualStudio说“不能隐式地将类型字符串转换为字符串[]” 你能告诉我怎么修理这个吗 string [] array = Console.ReadLine(); Console.ReadLine不返回数组,而是返回字符串: string line = Console.ReadLine(); 在您的代码中,变量array被声明为字符串数组,因此Console.ReadLine的结果无法分配给它。您可以使用字符串的to
string [] array = Console.ReadLine();
Console.ReadLine
不返回数组,而是返回字符串:
string line = Console.ReadLine();
在您的代码中,变量
array
被声明为字符串数组,因此Console.ReadLine
的结果无法分配给它。您可以使用字符串的tocharray()方法获取字符数组(char[])。然后可以使用LINQ或其他工具将每个字符转换为字符串
但请求非常奇怪。Console.ReadLine()返回一个字符串。如果你真的需要一个字符数组,你可以使用答案取决于你对“字符”的定义。如果您谈论的是代码点(即,
char
s),那么给出了几个答案。如果你谈论的是语言特征,那么这里有一种方法:
string[] array = GetAllCharacters(Console.ReadLine()).ToArray();
使用此方法:
using System.Globalization;
...
private static IEnumerable<string> GetAllCharacters(string text)
{
TextElementEnumerator elementEnumerator = StringInfo.GetTextElementEnumerator(text);
while (elementEnumerator.MoveNext())
yield return (string)elementEnumerator.Current;
}
使用系统全球化;
...
私有静态IEnumerable GetAllCharacters(字符串文本)
{
TextElementEnumerator elementEnumerator=StringInfo.GetTextElementEnumerator(文本);
while(elementEnumerator.MoveNext())
产生返回(字符串)elementEnumerator.Current;
}
好的。我的字符串变量是否自动成为数组?字符串可以被视为一个索引的字符列表,您可以使用ToCharArray方法获得一个实际的字符[]。问题是:为什么?你显然来自一个C世界——试着把字符串本身看作是独特的东西,而不是字符数组。