[英]How to bring each word letter in array c#
I have a problem in my code and I have no idea how to fix it.我的代码有问题,我不知道如何解决。 I need to copy every letter of the user entered word to array, but there is an error "Index was outside the bounds of the array".
我需要将用户输入的单词的每个字母复制到数组中,但出现错误“索引超出数组范围”。 I know that thir error means that I don't have correct size of the array, but I am using ReadLine and I can't enter static size.
我知道这个错误意味着我没有正确的数组大小,但是我使用的是 ReadLine 并且我无法输入静态大小。 It can be changed due user entered text.
它可以根据用户输入的文本进行更改。
Code:代码:
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[] { };
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You should define length of str
您应该定义
str
长度
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[text.Length];//<-- NOTE THIS
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You can use Linq to make this a one-liner:您可以使用 Linq 使其成为单行:
using System.Linq;
// ...
// ...
var separateLettersAsList = text.ToList();
var separateLettersAsArray = text.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.