【问题标题】:Get String after String.indexof in c#在 c# 中的 String.indexof 之后获取字符串
【发布时间】:2026-02-23 04:00:01
【问题描述】:

我目前正在用 C# 开发一个应用程序,我需要在字符串中某个字符之后获取子字符串。

else if (txtPriceLimit.Text.Contains('.') && char.IsNumber(e.KeyChar))
{
    int index = txtPriceLimit.Text.IndexOf('.');
    string pennies = txtPriceLimit.Text.Substring(index, txtPriceLimit.Text.Length);
    Console.WriteLine("Pennies: " + pennies);
}

出于某种原因,它不断提出IndexOutOfRangeException。如何获取从索引到末尾的字符串内容?

感谢您提供的任何帮助。

编辑: 刚刚发现我尝试过的各种建议似乎确实有效,只是它没有从按下文本字段的最后一个按钮中获取值。 我正在使用 KeyPress 事件来执行此操作。

例如,如果我输入 .123,它只会打印 12。然后如果我在末尾添加 4,它将打印 123

【问题讨论】:

  • 添加到甜甜圈的答案。您的Substring() 调用失败的原因是您要求从index 开始的txtPriceLimit.Text.Length 字符。这意味着您的字符串的整个长度必须是index + txtPriceLimit.Text.Length

标签: c# string substring


【解决方案1】:

您使用的overload of String.Substring 采用起始索引和指定长度。作为起始索引,您使用的是“.”的位置,但作为长度,您使用的是整个字符串的长度。如果index 大于 0,这将导致异常(如您所见)。

相反,只需使用这个:

string pennies = txtPriceLimit.Text.Substring(index + 1);

这将获得txtPriceLimit.Text .”位置之后的所有字符。注意我们需要给索引加1;否则 "." 将包含在生成的子字符串中。

【讨论】:

  • 谢谢,我确实尝试过,但它只获取 indexof 之前的值
  • @Boardy 不太清楚你在这里的意思,你能澄清一下吗? txtPriceLimit.Text 是否包含多个句点?
  • @Donut No 仅包含 1 个句点。抱歉,我误读了输出,除了最后一个字符外,它正在获取点之后的数字。例如,如果我输入 100.501 而不是打印 501,它将打印 50
  • @Boardy:看起来您是在 keydown 处理程序或类似的处理程序中执行此操作。您是否检查过txtPriceLimit.Text 已更新为包含用户刚刚输入的号码?
  • @Donut 我正在使用 KeyPress。当然调用 txtPriceLimit.Text 应该在调用该方法时获取最后输入的字符,但它似乎没有这样做
【解决方案2】:

尝试这样做

string pennies = txtPriceLimit.Text.Split('.')(1);

这里假设字符串中只有 1 个.,并且字符串中会有 1 个。

【讨论】:

  • 假设只有两个字符串部分。
  • string pennies = txtPriceLimit.Text.Split('.').LastOrDefault()
【解决方案3】:

看起来很多人都觉得这很有用,所以我想将我创建的一些代码贡献给社区。​​p>

这是我写的一个扩展方法,它将返回 this string txt 中的文本,跟随参数 string value:

清单 1:

public static string TextFollowing(this string txt, string value) {
  if (!String.IsNullOrEmpty(txt) && !String.IsNullOrEmpty(value)) {
    int index = txt.IndexOf(value);
    if (-1 < index) {
      int start = index + value.Length;
      if (start <= txt.Length) {
        return txt.Substring(start);
      }
    }
  }
  return null;
}

示例 1:

string exampleText = "My cat is bad.";
string afterCat = exampleText.TextFollowing("cat");
// afterCat = " is bad.";

对于没有接触过扩展方法的人,您可以从类似这样定义的工具中获得相同的结果:

清单 2:

public static string TextFollowing(string searchTxt, string value) {
  if (!String.IsNullOrEmpty(searchTxt) && !String.IsNullOrEmpty(value)) {
    int index = searchTxt.IndexOf(value);
    if (-1 < index) {
      int start = index + value.Length;
      if (start <= searchTxt.Length) {
        return searchTxt.Substring(start);
      }
    }
  }
  return null;
}

示例 2:

string exampleText = "My cat is bad.";
string afterCat = TextFollowing(exampleText, "cat");
// afterCat = " is bad.";

在上述每个示例中,如果 exampleText 是空字符串,则搜索值为 null 或空字符串,或者如果未找到搜索值,则结果字符串将为 null

我的工具列表中有这段代码,它在无数项目中的无数地方都使用过,而且总是很好用。

【讨论】:

    【解决方案4】:

    使用这个,这肯定会起作用:-

    else if (txtPriceLimit.Text.Contains('.') && char.IsNumber(e.KeyChar))
    {
        int index = txtPriceLimit.Text.IndexOf('.');
        string pennies = txtPriceLimit.Text.Substring(index+1, txtPriceLimit.Text.Length-(index+1));
        pennies=pennies+e.KeyChar.ToString();
        Console.WriteLine("Pennies: " + pennies);
    }
    

    【讨论】:

      【解决方案5】:

      甜甜圈的答案是正确的。

      因为 Substring 的第二个参数是 length 而不是 'end index',所以他的答案是更清晰的等价物:

      string pennies = txtPriceLimit.Text.Substring(index, index-txtPriceLimit.Text.Length);
      

      【讨论】:

      • 谢谢,我试过了,但仍然出现 indexoutofrange 异常
      • KeyPress 事件是让您接受或拒绝 - 文本尚未更新 - 并且待处理的字符在 e.KeyChar 中。如果您不拒绝输入 - 更改为使用 txtPriceLimit.TextChanged 事件 (msdn.microsoft.com/en-us/library/…)
      【解决方案6】:

      VisualBasic 版本

      查找子字符串的代码,如果找到,则返回尾随部分 - 紧跟在找到的子字符串后面(尾随结尾)的字符串的其余部分。

      jp2code 的回答以一种优雅的方式符合我的目的。除了示例之外,作者还表示该代码已经过一段时间的很好的尝试和测试。 VisualBasic 相当于他/她的代码:

      Imports System.Runtime.CompilerServices
      
      Module StringExtensions
          <Extension()>
          Public Function TextFollowing(txt As String, value As String) As String
              If Not String.IsNullOrEmpty(txt) AndAlso Not String.IsNullOrEmpty(value) Then
                  Dim index As Integer = txt.IndexOf(value)
                  If -1 < index Then
                      Dim start As Integer = index + value.Length
                      If start <= txt.Length Then
                          Return txt.Substring(start)
                      End If
                  End If
              End If
              Return Nothing
          End Function
      End Module
      

      代码已使用 VS Community 2017 进行了测试。

      使用示例

      Dim exampleText As String = "C-sharp to VisualBasic"
      Dim afterCSharp = exampleText.TextFollowing("to")
      'afterCSharp = " VisualBasic"
      

      扩展方法TextFollowing() 现在可用于String 对象。

      1. 第 1 行:exampleTextString,因此我们的扩展方法可用
      2. 第 2 行:exampleText.TextFollowing() 使用扩展方法

      互补法

      使用补充方法可能很有用 - 获取字符串的前面部分。互补的扩展方法被编写并放在一个组合代码模块中:

      Imports System.Runtime.CompilerServices
      
      Module StringExtensions
          <Extension()>
          Public Function TextFollowing(txt As String, value As String) As String
              If Not String.IsNullOrEmpty(txt) AndAlso Not String.IsNullOrEmpty(value) Then
                  Dim index As Integer = txt.IndexOf(value)
                  If -1 < index Then
                      Dim start As Integer = index + value.Length
                      If start <= txt.Length Then
                          Return txt.Substring(start)
                      End If
                  End If
              End If
              Return Nothing
          End Function
          <Extension()>
          Public Function TextPreceding(txt As String, value As String) As String
              If Not String.IsNullOrEmpty(txt) AndAlso Not String.IsNullOrEmpty(value) Then
                  Dim index As Integer = txt.IndexOf(value)
                  If -1 < index Then
                      Return txt.Substring(0, index)
                  End If
              End If
              Return Nothing
          End Function
      End Module
      

      使用示例

      Dim exampleText As String = "C-sharp to VisualBasic"
      Dim beforeVisualBasic = exampleText.TextPreceding("to")
      'beforeVisualBasic = "C-sharp "
      

      在我的用例中,有必要在使用这些扩展方法之前检查LargeString.Contains(SmallString)。为了更快地执行代码,这可以与上面介绍的扩展方法相结合,而我没有。这是因为没有遇到缓慢的情况,因此优先考虑代码的可重用性。

      【讨论】:

        最近更新 更多