【问题标题】:Substring starting at specific character count从特定字符数开始的子字符串
【发布时间】:2011-04-20 12:43:11
【问题描述】:

如何选择从特定字符数开始的字符串的最后一部分。 例如,我想获取第三个逗号之后的所有文本。但我收到一条错误消息 "StartIndex 不能小于零。"

Dim testString As String = "part, description, order, get this text, and this text"
Dim result As String = ""
result = testString.Substring(testString.IndexOf(",", 0, 3))

【问题讨论】:

  • 您想要在 第三个 逗号之后的文本,还是在 最后一个 逗号之后(在您给定的示例中恰好是相同的)?如果您输入"One, two, three, four, five and six",您的预期结果是什么? "four, five and six""five and six"?
  • 是第三个逗号后。我想把第四个放在那里,为了清楚起见,我对其进行了编辑。

标签: vb.net string substring


【解决方案1】:

这是我的两分钱:

string.Join(",", "aaa,bbb,ccc,ddd,eee".Split(',').Skip(2));

【讨论】:

  • @tmax np,我相信我将来到现在都可以使用它!
【解决方案2】:

代码 "testString.IndexOf(",", 0, 3)" 找不到第三个逗号。它找到从位置 0 开始的第一个逗号,查看前 3 个位置(即字符位置 0、1、2)。

如果您想要最后一个逗号之后的部分,请使用以下内容:

Dim testString As String = "part, description, order, get this text"
Dim result As String = ""
result = testString.Substring(testString.LastIndexOf(",") + 1)

注意 +1 移动到逗号后面的字符。您确实还应该首先找到索引并添加检查以确认索引不是 -1 并且 index

【讨论】:

    【解决方案3】:

    替代方案(我假设您想要最后一个逗号之后的所有文本):

    使用 LastIndexOf:

    ' You can add code to check if the LastIndexOf returns a positive number
    Dim result As String = testString.SubString(testString.LastIndexOf(",")+1)
    

    正则表达式:

    Dim result As String = Regex.Replace(testString, "(.*,)(.*)$", "$2")
    

    【讨论】:

    • 第三个逗号后的所有文本,Dim testString As String = "part, description, order, get this text, and this text"
    【解决方案4】:

    indexOf 的第三个参数是要搜索的字符数。您正在从 0 开始搜索 , 以查找 3 字符 - 即在字符串 par 中搜索不存在的逗号,因此返回的索引为 -1,因此您的错误。我认为您需要使用一些递归:

    Dim testString As String = "part, description, order, get this text"
    Dim index As Int32 = 0
    
    For i As Int32 = 1 To 3    
      index = testString.IndexOf(","c, index + 1)
      If index < 0 Then
        ' Not enough commas. Handle this.
      End If
    Next
    Dim result As String = testString.Substring(index + 1)
    

    【讨论】:

    • 我以前做过这种方法,但正在寻找一种方法。
    【解决方案5】:

    IndexOf 函数只查找指定字符的“First”。最后一个参数(在您的情况下为 3)指定要检查的字符数而不是出现次数。

    参考Find Nth occurrence of a character in a string

    此处指定的函数查找字符的第 N 次出现。然后对返回的事件使用 substring 函数。

    或者,你也可以使用正则表达式来查找第n次出现。

    public static int NthIndexOf(这个字符串目标,字符串值,int n) { 匹配 m = Regex.Match(target, "((" + value + ").*?){" + n + "}"); 如果(m.成功) { 返回 m.Groups[2].Captures[n - 1].Index; } 别的 { 返回-1; } }

    【讨论】:

      【解决方案6】:

      我想这就是你要找的东西

          Dim testString As String = "part, description, order, get this text"
          Dim resultArray As String() = testString.Split(New Char() {","c}, 3)
          Dim resultString As String = resultArray(2)
      

      【讨论】:

        猜你喜欢
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多