【问题标题】:Get Substring of a String by Startindex and Endindex通过 Startindex 和 Endindex 获取字符串的子字符串
【发布时间】:2018-12-13 09:56:43
【问题描述】:

我尝试从字符串Data:[1,2,3] 中提取1,2,3 作为字符串。使用以下代码执行此操作会给我Error Index and length must refer to a location within the string,看起来我完全失明,但我看不出有什么问题。谁能帮帮我?

Sub Main()
    Dim name As String = "Data:[1,2,3]"
    Console.Write(name.Substring(6, name.Length - 1))
    Console.Read()
End Sub

【问题讨论】:

  • 您正在寻找Console.Write(name.Substring(6, 5))。后一个数字是计数而不是索引。
  • Console.Write(Mid(name, 6))

标签: string vb.net


【解决方案1】:

String.Substring 中的第二个参数是长度,即应该从第一个参数的索引中获取的字符数。您应该寻找括号:

Dim startIndex = name.IndexOf("["c)
If startIndex >= 0 Then
    Dim endIndex = name.IndexOf("]"c, startIndex)
    If endIndex >= 0 Then
       startIndex += 1 ' because you dont want to include the  brackets
       Dim data = name.Substring(startIndex, endIndex - startIndex)
    End If
End If

【讨论】:

  • 谢谢,这是我一直在寻找的,因为我需要在不同的字符串长度上使用它。好期待。
猜你喜欢
  • 2013-05-19
  • 2015-02-03
  • 2011-03-15
  • 1970-01-01
  • 2015-07-07
  • 2021-12-11
  • 2016-04-28
  • 2011-12-27
  • 1970-01-01
相关资源
最近更新 更多