我有一个包含此内容的.txt文件,例如:
1
Hey, how are u
Ist everything ok ?
I hope u are well
2 I'm fine thanks
Nice to hear from u
3 Sounds great
What are u doing now ?
Hope u enjoy your stay
我需要一个可以给出数字的方法,例如2,程序应该在新的txt文件中将数字2之后的整个文本复制到数字3。楼下我发布了一个如何识别线路的解决方案,但现在我不知道如何复制文件的某个部分
答案 0 :(得分:0)
public static void RunSnippet()
{
string input =
"1 Hey, how are u\n" +
"\n" +
"2 I'm fine thanks\n" +
"\n" +
"3 Sounds great";
Console.WriteLine(GetLine(3, input));
}
static string GetLine(int number, string content)
{
return Regex.Split(content, "\n").First(l=> l.StartsWith(number.ToString()));
}
答案 1 :(得分:-1)
使用正则表达式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"1 Hey, how are u\n" +
"\n" +
"2 I'm fine thanks\n" +
"\n" +
"3 Sounds great";
string pattern = @"^(?'index'\d+)\s+(?'value'.*)";
Regex expr = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = expr.Matches(input);
Dictionary<int, string> dict = new Dictionary<int, string>();
foreach(Match match in matches)
{
dict.Add(int.Parse(match.Groups["index"].Value), match.Groups["value"].Value);
}
string sentence2 = dict[2];
}
}
}