【问题标题】:c# Split Strings Into Separate Text Boxes [closed]c#将字符串拆分为单独的文本框[关闭]
【发布时间】:2014-05-08 16:43:34
【问题描述】:

我是初学者。我有要读取文本文件的代码,以及如何将字符串放入文本框中的部分内容。文本文件的格式如 DREC: 04HF;然后下一个以相同的格式开始。我需要从文本文件中读取它并将其拆分为 2 个单独的文本框 (3,4),位于 a : 或 a ; .谢谢你的帮助。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog of = new OpenFileDialog();
        of.ShowDialog();
        textBox1.Text = of.FileName;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        StreamReader sr = new StreamReader(textBox1.Text);
        textBox2.Text = sr.ReadToEnd();
        sr.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        int lcount;
        string s;
        int i;
        lcount = textBox2.Lines.Length;
        s = textBox2.Lines[0];
        for (i = 0; i < lcount; i++)
        {

            textBox4.Text = textBox2.Lines[i];
        }
        textBox4.Text = s;
    }
}

【问题讨论】:

  • 好的,谢谢分享。这是一个问题,而不是一个问题。
  • 我可以给你一个大概的想法。为每个文本框保存一个字符串或一个 stringBuilder,开始拆分文本并将部分附加到它们各自的 stringBuilder。毕竟,在您的文本框中查看它们。
  • .Split(new Char [] {' ': ';' });在你的字符串上调用它
  • @tnw 我不要求一个完整的解决方案只是建议或下一步要走的路,对不起

标签: c# string loops textbox split


【解决方案1】:

我需要更好地描述你在做什么,但也许这会有所帮助

//split apart segments
string[] split1 = textBox2.Text.Split(';');
foreach (string segment in split1)
        {
            //split sub-segment
            string[] split2 = segment.Split(':');

            //check if it's valid
            if (split2.Count().Equals(2))
            {
                textBox3.Text += String.Format("{0}{1}", split2[0].Trim(), Environment.NewLine);
                    textBox4.Text += String.Format("{0}{1}", split2[1].Trim(), Environment.NewLine);
            }
            else
            {
                throw new ArgumentException("Invalid Segment");
            }
        }

【讨论】:

  • 我只有一个文本文件,其中包含如下行: DCSD: 98JDSK; KLDD34:MWEP4;等等,我只需要将它们并排显示到 2 个不同的文本框中。就这些
  • 所以 DCSD 将在 box1 中,而 98JDSK 将在 box2 中?那些文本框是多行的?
  • 是的,正确的。我只需要它们在单独的文本框中彼此相对。
  • 我能用你的代码完美地得到它。非常感谢,Tsukasa
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
相关资源
最近更新 更多