【问题标题】:Getting data from textbox into array从文本框中获取数据到数组中
【发布时间】:2014-08-25 11:50:08
【问题描述】:

如何将用户在文本框中输入的数据流式传输到int数组中?假设我有一个带有 2 个文本框、按钮和缓冲区的窗口,在界面中不可见。
我希望在单击button1 后将来自textbox1(例如CAT)的数据保存到int buffer[255]。然后,点击button2 后,CAT 应该会出现在textbox2 中,并且正在从buffer 中删除。
应该是这样的:

int buffer[255]={0};
//user entered 'CAT' in textbox1
//clicking button1
//now:
buffer[0]=[67]; //67 = 'C' in ASCII
buffer[1]=[65];
buffer[2]=[84];
//clicking button2
//in read-only textbox2 'CAT' appears
//now:
buffer[]={0};

我想在 textbox2 中显示单词时需要进行一些转换(for loopSystem.Convert.ToChar(buffer[i])),但最让我困惑的是如何将文本从 textbox1 保存到 buffer

好的,谢谢回复,现在我需要让我的按钮工作,但不知道为什么,我现在有了这个方法:

public int saveToBuffer(string text)
        {
            string txt = text;
            int[] receivedBuffer = new int[255];
            int count = 0;
            //int i = 0;

            foreach(char c in txt)
            {
                receivedBuffer[count] = c;
                count++;
            }
            return receivedBuffer[255];
        }

它将文本从 textbox1 返回到数组 receivedBuffer。我也有这个按钮:

private void saveToBufferButton_Click(object sender, EventArgs e)
        {

        }

我不知道该放什么 beetwen {} 让它工作。

【问题讨论】:

  • 您可以循环遍历textbox1.Text 直到textbox1.Text.Length 并将每个字符放入缓冲区索引中。

标签: c# c++ arrays visual-studio-2010


【解决方案1】:

感谢我在此示例中没有使用静态定义的缓冲区,希望这将帮助您获得所需的解决方案:

int[] buffer = "CAT".Select(Convert.ToInt32).ToArray();
string result = new string(buffer.Select(Convert.ToChar).ToArray());

将上面示例中的“CAT”替换为 textbox1.Text。

【讨论】:

    【解决方案2】:

    来自 Rob Epsteing 的出色回应,只是添加了一种不使用 LINQ 的不同方法,这可能会很好地了解 Rob Epstein 在 2 个语句中所展示的内容。

            string text = "CAT";
            int[] buffer = new int[text.Length];
            int count = 0;
            //add to buffer
            foreach(char c in text)
            {
                buffer[count] = c;
                count++;
            }
    
            //from buffer to text
            StringBuilder builder = new StringBuilder();
            foreach(char c in buffer)
            {
                builder.Append(c);
            }
            text = builder.ToString();
    

    【讨论】:

      【解决方案3】:

      从字符串中检索 ASCII 码的简单方法是:

      string value = textbox1.Text;
      
      // Convert the string into a byte[].
      byte[] asciiBytes = Encoding.ASCII.GetBytes(value);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-11
        • 1970-01-01
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多