【问题标题】:Removing strings from a list line by line逐行从列表中删除字符串
【发布时间】:2022-08-16 21:13:07
【问题描述】:
我的问题是,如果我有一个如下所示的列表,
var list = new List<string>();
list.Add(\"12345\");
list.Add(\"Words\");
list.Add(\"Are\");
list.Add(\"Here\");
list.Add(\"13264\");
list.Add(\"More\");
list.Add(\"Words\");
list.Add(\"15654\");
list.Add(\"Extra\");
list.Add(\"Words\");
我希望能够从列表中删除所有以数字开头的字符串,并将它们之间的字符串连接起来,使其如下所示,
字在这里
更多的话
多余的话
这个逻辑看起来怎么样?以下是我一直在尝试做的事情,但是我无法首先知道如何删除带有数字的字符串,更不用说在删除带有数字的字符串时创建换行符了。
foreach (string s in list)
{
if (s.StartsWith(\"1\"))
s.Remove(0, s.Length);
else
String.Concat(s);
}
foreach (string p in list)
Console.WriteLine(p);
标签:
c#
string
list
concatenation
【解决方案1】:
您可以尝试以下方法:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var list = new List<string>();
list.Add("12345");
list.Add("Words");
list.Add("Are");
list.Add("Here");
list.Add("13264");
list.Add("More");
list.Add("Words");
list.Add("15654");
list.Add("Extra");
list.Add("Words");
var resultStrings = new List<string>();
string currentString = "";
foreach (string s in list)
{
if (s.StartsWith("1"))
{
resultStrings.Add(currentString);
currentString = "";
}
else
{
currentString += s + " ";
}
}
resultStrings.Add(currentString);
foreach (string p in resultStrings)
Console.WriteLine(p);
}
}
【解决方案2】:
另一种方法
var list = new List<string>();
list.Add("12345");
list.Add("Words");
list.Add("Are");
list.Add("Here");
list.Add("13264");
list.Add("More");
list.Add("Words");
list.Add("15654");
list.Add("Extra");
list.Add("Words");
var lines = new List<KeyValuePair<int, string>>();
var currentIndex = 0;
foreach (var line in list)
{
if (line.Length == 0)
{
continue;
}
var firstChar = line.Substring(0, 1)
.ToCharArray()
.First();
if (char.IsNumber(firstChar))
{
currentIndex++;
continue;
}
lines.Add(new KeyValuePair<int, string>(currentIndex, line));
}
foreach (var lineGroup in lines.GroupBy(x => x.Key))
{
Console.WriteLine(string.Join(" ", lineGroup.Select(x => x.Value)));
}