【问题标题】:How to get substring with an unknown length [closed]如何获取长度未知的子字符串[关闭]
【发布时间】:2014-11-20 00:51:02
【问题描述】:

我有一个字符串,其中表名每次都会更改。如何找到子字符串并使用它的值。例如

示例字符串:

表“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 执行相同的操作,表的名称每次都会更改?

【问题讨论】:

  • 您可以在您的问题中添加一些示例字符串吗?
  • 这将有助于查看字符串值可能是什么的一些示例,同样重要的是,您希望从中得到什么。我怀疑你会寻找string.Split,但从你现在向我们展示的内容中无法判断。
  • @Matthew:我只需要表名作为值。我正在为“计数”做同样的事情,这很容易,但是当表的名称每次更改时会发生什么

标签: c# string substring indexof


【解决方案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);

【讨论】:

  • 谢谢。解决了我的问题
猜你喜欢
  • 2019-12-24
  • 2021-11-28
  • 2014-01-10
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 2019-09-02
  • 2021-12-04
相关资源
最近更新 更多