2013-07-03 19 views
0

讀取特定值我有一個字符串的行:C#中的字符串

colors numResults="100" totalResults="6806926"

我想從上面的字符串 提取值6806926這怎麼可能?

到目前爲止,我已經使用StringReader讀取由行的所有串線。 那我該怎麼辦?

+0

問題是什麼? –

+0

XML文件中的哪一行? – Matheno

+0

聲明丟失。 –

回答

0

考慮這是MYTEXT字符串類型的變量

現在

Mytext.Substring(Mytext.indexof("totalResults="),7); 

//功能的indexOf w ^生病返回點何在值開始, // 7是要提取

我使用的類似的這種........

+0

那麼,你也可以'返回6806926;'(諷刺)。我認爲'totalResults'的值會有所不同,並且它不會總是隻有7個字符長。 – Corak

0

您可以閱讀Linq2Xml,numResults和使用totalResults是屬性<colors numResults="100" totalResults="6806926">,所以你可以簡單地用n myXmlElement.Attributes("totalResults")得到它。

2

我敢肯定,也有一個正則表達式,但這種string方法也應該工作:

string xmlLine = "[<colors numResults=\"100\" totalResults=\"6806926\">]"; 
string pattern = "totalResults=\""; 
int startIndex = xmlLine.IndexOf(pattern); 
if(startIndex >= 0) 
{ 
    startIndex += pattern.Length; 
    int endIndex = xmlLine.IndexOf("\"", startIndex); 
    if(endIndex >= 0) 
    { 
     string token = xmlLine.Substring(startIndex,endIndex - startIndex); 
     // if you want to calculate with it 
     int totalResults = int.Parse(token); 
    } 
} 

Demo

0

此功能將分裂charactors的長度串入鍵值對的列表,然後你就可以拉出任何你需要

 static List<KeyValuePair<string, string>> getItems(string s) 
    { 
     var retVal = new List<KeyValuePair<String, string>>(); 

     var items = s.Split(' '); 

     foreach (var item in items.Where(x => x.Contains("="))) 
     { 
      retVal.Add(new KeyValuePair<string, string>(item.Split('=')[0], item.Split('=')[1].Replace("\"", ""))); 
     } 

     return retVal; 
    } 
0

您可以使用正則表達式:

string input = "colors numResults=\"100\" totalResults=\"6806926\""; 
string pattern = "totalResults=\"(?<results>\\d+?)\""; 
Match result = new Regex(pattern).Match(input); 
Console.WriteLine(result.Groups["results"]); 

一定要甲肝E本包括:

using System.Text.RegularExpressions;