2014-09-25 93 views
-3

我有一個字符串,其中的表名每次更改。如何找到字符串,並使用其value.eg如何獲取未知長度的子字符串

樣品字符串:

表 'ProductCostHistory'。計數1,邏輯5,物理0

if (line.Contains("Count")) 
{ 
    int index = line.IndexOf("Count"); 
    string substring2 = line.Substring(index, 12); 
    string scancountval = substring2.Substring(11); 
} 

現在我該怎麼辦了表ProductCostHistory,其中表的名稱更改每次都一樣嗎?

+0

請再問一次 – 2014-09-25 09:47:28

+0

您可以在您的問題中添加一些示例字符串嗎? – Shaharyar 2014-09-25 09:47:36

+0

這將有助於看到字符串值可能的一些示例,同樣重要的是,您希望從中獲得什麼。我懷疑你會找'string.Split',但是根據你現在給我們展示的內容是不可能的。 – 2014-09-25 09:49:00

回答

1

您可以使用字符串方法,如String.SubstringString.IndexOf。後者用於查找給定子字符串的起始索引。如果找不到它,它將返回-1,所以這也可以用來避免額外的String.Contains -check。它也有一個重載取整數到指定的字符位置開始搜索(以下用於endIndex):

string text = "Table 'ProductCostHistory'. Count 1, logical 5, physical 0"; 
int index = text.IndexOf("Table '"); 
if(index >= 0) // no Contains-check needed 
{ 
    index += "Table '".Length; // we want to look behind it 
    int endIndex = text.IndexOf("'.", index); 
    if(endIndex >= 0) 
    { 
     string tableName = text.Substring(index, endIndex - index); 
     Console.Write(tableName); // ProductCostHistory 
    } 
} 

注意,在.NET比較字符串大小寫敏感的,如果你想有一個案例 - 敏感性比較:

int index = text.IndexOf("Table '", StringComparison.CurrentCultureIgnoreCase); 
+0

謝謝。解決了我的問題 – Kira 2014-09-25 10:23:36