简体   繁体   English

c# - 如何将数组中的每个单词字母带入

[英]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.

相关问题 如何使用c#代码制作每个单词的第一个字母 - how to make 1st letter of each word capital using c# code 如何使用 2d arrays c# 读取文件并将每个单词存储在数组中的行数组中 - How to read a file and store each word in a array in a array of lines using 2d arrays c# 如何在 C# 控制台中更改字符串中每个字母的前景色? - How to change Foreground Color of each letter in a string in C# Console? 如何在C#中的字符串中的每个字母之间添加符号? - how to add a sign between each letter in a string in C#? C#将一个单词拆分为字符,然后对每个字母的ASCII码求和以求和 - C# Splitting a word into characters and then summing the ASCII code of each letter to get a sum 正则表达式每个单词的首字母大写由空格和 3 到 29 个字符长...C# - Regex first letter of each word Upper Case separated by spaces and 3 to 29 character long…C# C#帮助绘图信(文字游戏) - C# Help drawing letter (Word Game) 如果单词中有imputfield字母,则C#进行计数 - C# count if a imputfield letter is in a word 如何访问并将从文件中读取的字符串数组中的每个单词写入到C#中的新文件中? - how to access and write each word in string array read from a file onto a new file in c#? (C#) - 将Split中的每个单词存储在一个数组中 - (C#) - store each word between Split in an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM