2014-04-04 54 views
-1

我有一個文本文件,其中包含我可以使用的信息,以便獲得一個string.substring(位置,長度) 。包含我想要做的位置和長度如何從txt文件中找到子串的位置和長度

Element Length Position 
    Name  30  1 
    Age   2  31 
    ID   1  33 
    DOB   2  34 

// this is a sample data 
String Data = "NAMENAMENAMENAMENAMENAMENAMEAGE119861126" 

.txt文件是環通從文本文件中的規則,並得到 字符串數據的字符串。

+0

你隨機txt文件保存的長度和位置值? – Relax

+1

什麼不起作用? –

+1

這是更多的「這是我的任務,你能爲我做」問題 – yorah

回答

1

使用File.ReadLinesString.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' 
+0

你能向我解釋substringInfo變量你怎麼知道在哪裏拆分或跳過? – HXD

+0

@HXD:LINQ查詢的哪一部分不明白?第一個跳過所有空行,第一行不是空的,即標題。然後它會按空格或製表符分隔每一行,因爲您的示例數據似乎是通過製表符分隔的,但我不確定這是否正確。然後我檢查字符串[]是否包含三個元素,否則這行將被忽略。這三個令牌用於初始化一個匿名類型。在'foreach'中執行LINQ查詢並將結果寫入控制檯。 –

相關問題