C# 在.txt文件中搜索特定行并将其复制到另一个文件c中#
我有一个包含此内容的.txt文件,例如:C# 在.txt文件中搜索特定行并将其复制到另一个文件c中#,c#,file-io,C#,File Io,我有一个包含此内容的.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和程序应该复制整个文本后,数字2到数字3在一个新的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和程序应该复制整个文本后,数字2到数字3在一个新的txt文件。楼下我发布了一个如何识别行的解决方案,但现在我不知道如何复制文件的某个部分
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];
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Text.RegularExpressions;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串输入=
“1嘿,你好吗\n”+
“\n”+
“2我很好,谢谢”+
“\n”+
“3听起来很棒”;
字符串模式=@“^(?'index'\d+)\s+(?'value'.*)”;
Regex expr=新的Regex(模式,RegexOptions.Multiline);
MatchCollection matches=expr.matches(输入);
Dictionary dict=新字典();
foreach(匹配中的匹配)
{
dict.Add(int.Parse(match.Groups[“index”].Value),match.Groups[“Value”].Value);
}
字符串语句2=dict[2];
}
}
}
您想要一个控制台应用程序,在其中输入一个数字,然后返回一行(以该数字开头)并将其写入文件?您尝试了什么?如果您向我们展示一些代码,我们可以帮助您修复错误。您可以在此处查看一些示例代码:如果第一行中的数字是有序的,则只需通过行进行简单的增量即可。但是如果数字是随机的(看起来不是),则解析行的第一个char
,然后将其与数字进行比较if(line_num==(int)Char.GetNumericValue(line[0]))
我知道如何读取我的txt文件,我的问题是我不知道如何在代码中查找特殊的数字以及如何复制文本直到下一个数字。楼下的例子不起作用,因为我把所有东西都保存在am external txt文件中,上面有200多个例子,我还在添加东西
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()));
}