我有一个文本文件,其中包含我可以使用的信息 string.substring(position,length)。
// this is a sample data
String Data = "NAMENAMENAMENAMENAMENAMENAMEAGE119861126"
包含位置和长度的.txt文件
Element Length Position
Name 30 1
Age 2 31
ID 1 33
DOB 2 34
我想要做的是从文本文件中循环规则并获取子字符串 字符串数据。
答案 0 :(得分:1)
使用File.ReadLines
和String.Split
,这里有一些LINQ-magic:
String Data = "NAMENAMENAMENAMENAMENAMENAMEAGE119861126";
var substringInfos = File.ReadLines("Path")
.SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1) // skip empty lines and the header
.Select(l => l.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))
.Where(split => split.Length == 3)
.Select(split => new
{
Element = split[0],
Length = int.Parse(split[1]),
Position = int.Parse(split[2])
});
foreach (var info in substringInfos)
{
string substring = Data.Substring(info.Position, info.Length);
Console.WriteLine("Element: '{0}' Value: '{1}'", info.Element, substring);
}
结果:
Element: 'Name' Value: 'AMENAMENAMENAMENAMENAMENAMEAGE'
Element: 'Age' Value: '11'
Element: 'ID' Value: '9'
Element: 'DOB' Value: '86'