2014-09-25 90 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