在多行中分割位于特定行位置的多行文本
本文关键字:位置 文本 于特定 分割 | 更新日期: 2023-09-27 18:13:50
我有一个多行的文本文件:
12345 beautiful text in line01
95469 other text in line02
16987 nice text in line03
(etc...)
并想要这个:
12345
beautiful text in line01
95469
other text in line02
16987
nice text in line03
所以,对于每一行,在位置5,我需要一个新的文本字符串行。
尝试用string.Remove().Insert()
插入'n
,但仅适用于第一行。我该怎么做呢?
编辑按要求添加的代码在input.txt中有多行文本文件。
StreamReader myReader = new StreamReader("input.txt");
string myString00 = myReader.ReadLine();
string myStringFinal = myString00;
myStringFinal = myStringFinal.Remove(5, 1).Insert(5, "'n");
myReader.Close();
FileStream myFs = new FileStream("output.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter mySw = new StreamWriter(myFs);
Console.SetOut(mySw);
Console.WriteLine(myStringFinal);
Console.SetOut(tmp);
Console.WriteLine(myStringFinal);
mySw.Close();
Console.ReadLine();
您可以尝试使用Regex
var subject = @"12345 beautiful text in line01
95469 other text in line02
16987 nice text in line03";
var expected = Regex.Replace(subject,@"('d{5})'s?","$1'r'n");
基本上,这将找到后跟空格(可选)的5个数字,如果找到,将其替换为数字和新行。
只有当数字恰好是5个字符时才有效。
string input = @"12345 beautiful text in line01
95469 other text in line02
16987 nice text in line03";
var lines = input.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var formattedLines = lines
.Select(x => new
{
Number = int.Parse(x.Substring(0, 5)),
Data = x.Substring(5).TrimStart()
})
.ToList();
formattedLines
将是行的集合,Number
和Data
保存行中的信息。
var firstLinesData = formattedLines[0].Data;
那么现在,让你的输出格式:
StringBuilder builder = new StringBuilder();
foreach (var item in formattedLines)
{
builder.AppendLine(item.Number.ToString());
builder.AppendLine(item.Data);
}
string output = builder.ToString();
在每一行上循环。使用substring (http://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx)将前5个字符作为字符串获取。使用字符串生成器并添加第一部分,抓取下一部分并添加到字符串生成器