2015-06-15 83 views
-2

我想從c#中的文本文件中只提取數字。我的文本文件就像下面我想從c中的文本文件中只提取數字#

xasd 50 ysd 20 zaf 40 bhar 60 

我想瀏覽一個文件openfileDialoug和讀取該文件,並從同一個文件中提取號碼,需要將這些值與恆定值進行比較說60。我需要顯示有多少數字比這個常數更多。如果這些數字大於60,那麼我需要將更大的值的數量與現有的文本一起附加到richtextBox。

+0

可以告訴你多一點的文本文件作爲樣本? – Ali

回答

0

如果你的文件總是這樣,你已經證明,那麼你可以很容易地把它分解和解析:

string filePath = ""; // from OpenFileDialog 

string fileContents = File.ReadAllText(filePath); 
string[] values = fileContents.Split(); 
int valueInt, greaterValuesCount = 0;  

foreach (var value in values) 
{ 
    if (int.TryParse(value, out valueInt)) 
    { 
     greaterValueCount++; 
     // Do something else here 
    } 
} 
+0

非常感謝你..它幫助了我很多。 –

1

可以使用Int32.TryParse(string s,out int result)方法。如果字符串s可以被解析爲一個整數並將值存儲在int結果中,則返回true。此外,您可以使用String.Split(Char[])方法分割您從文本文件讀取的行。

string line = fileObject.ReadLine(); 
int constant = 60; //For your example 
int num = 0; 
string []tokens = line.Split(); //No arguments in this method means space is used as the delimeter 
foreach(string s in tokens) 
{ 
    if(Int32.TryParse(s, out num) 
    { 
     if(num > constant) 
     { 
      //Logic to append to Rich Text Box 
     } 
    } 
} 
1

正則表達式是要找到數字的字符串,它是OP需要一個優雅的方式,是這樣的:

string allDetails = File.ReadAllText(Path); 

result = Regex.Match(allDetails, @"\d+").Value; 

現在resultString將包含所有提取的整數

如果您也想照顧負數=,然後做這個修改

result = Regex.Match(allDetails, @"-?\d+").Value; 

希望這會有所幫助,請查看以下職位:

Find and extract a number from a string