【问题标题】:Returning a string with one line per index返回每个索引一行的字符串
【发布时间】:2014-03-17 12:25:32
【问题描述】:

多行,textBox1.Text =

RGYR
RGGB
RGRG
RYBG
RYYB
GBRY
RYBG

但是,我希望游戏一次读取每一行;

Color[] colourset = newSequence(textBox1.Text.Length);

正在读取整个字符串,而没有预料到每隔 4 个字符就会换行,这会搞砸一切。

如何让它在多行文本框中每个索引读取一行?

上下文代码:

private Color[] sequence;
//Declare dictionary
private Dictionary<char,Color>  stringTocolor = new Dictionary<char,Color>();

public SimonSays ()
{
    //add content to Dictionary
    stringTocolor.Add('R', Color.Red);
    stringTocolor.Add('G', Color.Green);
    stringTocolor.Add('B', Color.Blue);
    stringTocolor.Add('Y', Color.Yellow);

    Color[] colourset = newSequence(textBox1.Text.Length); //This may be the problem? Reading entire string length instead of just one line at a time??
}

public Color[] newSequence(int length)
{
    Color[] array = new Color[length];
    //check dictionary has the char key or not
    for (int i = 0; i < textBox1.Text.Length; i++)
    {
        if (stringTocolor.ContainsKey(textBox1.Text[i]))
        {
             array[i] = stringTocolor[textBox1.Text[i]];
        }
        //give alert if wrong key
        else
        {
             MessageBox.Show("Wrong Colour input at index " + i + " of textbox string!");
        }
    }
    this.sequence = array;
    return array;
}
public void newSequence (Color [] sequence)
    {
    this.sequence= //read next line of string
    }

【问题讨论】:

  • 弄清楚换行符和String.Split是什么?看来您需要先这样做。

标签: c# arrays string textbox multiline


【解决方案1】:

您可以通过Lines 属性进行索引:

 for(int i = 0 ; i < textBox1.Lines.Length; i++)
      Color[] colourset = newSequence(textBox1.Lines[i].Length);

【讨论】:

  • 感谢您的留言!我得到“索引 4 和 5 的颜色输入错误”
【解决方案2】:

如何让它在多行文本框中每个索引读取一行?

您可以根据EnvironMent.NewLine 拆分字符串,然后在循环中使用索引获取所需的项目。

试试这个:

var lines = textBox1.Text.Split(new [] {Environment.NewLine},
                                        StringSplitOptions.RemoveEmptyEntries);

【讨论】:

    【解决方案3】:

    我做到了,结果就是这样。

    Color[] colourset = newSequence(textBox1.Lines[0].Length);
    

    【讨论】:

      猜你喜欢
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多