[英]Multiline textbox entries not seperated
為什么 -ABC12 以外的其他字符串不分開? 在此處輸入代碼
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;
namespace multiline_textbox_seperation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String[] lines = textBox2.Text.Split(',');
List<string> List = new List<string>();
List.AddRange(lines);
for (int i = 0; i < List.Count; i++)
{
textBox1.Text += List[i] + "\r\n";
}
List<String> PossitiveList = new List<String> { };
List<String> NegativeList = new List<String> { };
for (int i = 0; i < List.Count; i++)
{
if (List[i].StartsWith("-")) { NegativeList.Add(List[i]); }
if (List[i].StartsWith("+")) { PossitiveList.Add(List[i]); }
}
listBox1.DataSource = NegativeList;
listBox2.DataSource = PossitiveList;
}
}
}
字符串的結果:
string input = "-ABC12, +ABC12, -BAC12, -ACC12, +EAC12, -BBC12, -CBC12, +GABC12, +ACC12, +CBC12, +BBC12"
在 textbox2 中輸入的是:
如果你仔細觀察,你會發現中間有空格。
而不是做: List[i].StartsWith("-")
或List[i].StartsWith("+")
,做:
List[i].Trim().StartsWith("-")
List[i].Trim().StartsWith("+")
我會簡化一點:
private void button1_Click(object sender, EventArgs e)
{
var values = new List<string>(textBox2.Text.Split(','))
.Select(x => x.Trim()).ToList();
textBox1.Lines = values.ToArray(); // optional
var PositiveList = values.Where(x => x.StartsWith("+")).ToList();
var NegativeList = values.Where(x => x.StartsWith("-")).ToList();
listBox1.DataSource = NegativeList;
listBox2.DataSource = PositiveList;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.