c# 一串數字“1122331111155”,要輸出到DataGridview控件上,但是要逐個數字讀取,如果上一個數字與下一個相同,則排成一列,不相同,則另外排成一列。如“1122331111155”,輸出的效果是,列一:11,列二:22,列三:33,列四:11111,列五:55。 如下: string numberStr = "1122331111155"; string temp = string.Empty; string column = string.Empty; List<string> lstColumn = new List<string>(); numberStr.ToCharArray().ToList().ForEach((char c) => { if (string.IsNullOrEmpty(temp)) { temp = c.ToString(); } if (temp == c.ToString()) { column += c; } else { lstColumn.Add(column); temp = c.ToString(); column = temp; } }); lstColumn.Add(column); lstColumn.ForEach((string columnName) => { this.dataGridView1.Columns.Add(new DataGridViewColumn { CellTemplate = new DataGridViewTextBoxCell(), Name = columnName }); }); 其二 MatchCollection mc = Regex.Matches("1122331111155", @"(.)\1*"); List<string> columns = new List<string>(); foreach (Match m in mc) { columns.Add(m.Value); } columns.ForEach((string columnName) => { this.dataGridView1.Columns.Add(new DataGridViewColumn { CellTemplate = new DataGridViewTextBoxCell(), Name = columnName }); });