使用File.ReadLines
和String.Split
,這裏是一些LINQ魔:
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'
你隨機txt文件保存的長度和位置值? – Relax
什麼不起作用? –
這是更多的「這是我的任務,你能爲我做」問題 – yorah