剥去字符串的前5个字符

时间:2014-08-05 13:47:40

标签: asp.net vb.net

我有以下代码;

For Each test In gvForecasts.Columns
            Dim test2 = test.caption
            test2 = test2.Substring(0, 5)
        Next

test2将返回值“第1周”

我希望能够删除此字符串,使其仅返回“1”

但是会返回以下错误消息; “索引和长度必须指代字符串中的位置。”

任何帮助都会很棒!

4 个答案:

答案 0 :(得分:4)

Substring方法的第一个参数是你想要开始的索引,下一个参数是你想要抓取的字符数。

试试这段代码:

If test2.Length > 5 Then
            test2 = test2.Substring(5, 1)
Else
            Throw New Exception("Invalid source string")
End If

&安培;如果您只想消除前5个字符,可以使用以下代码:

If test2.Length > 5 Then
            test2 = test2.Substring(5)
Else
            Throw New Exception("Invalid source string")
End If

答案 1 :(得分:1)

Your usage of vb.net's subString() method is incorrect.

具体来说,您的方法是抓取字符串的前5个字符(Week_)。

它应该用作subString(5)从第5个开始返回所有字符。

答案 2 :(得分:1)

您想获取每个标记用空格分隔的字符串的最后一个数字吗?

您可以使用String.Split和此查询:

For Each test In gvForecasts.Columns
    Dim words = test.caption.Split() ' splits by all white-space characters
    Dim num As Int32
    Dim numberParts = From word in words Where Int32.TryParse(word, num)
    Dim weekNumber As String = numberParts.LastOrDefault()
Next

Side-Note:正如Psychemaster已经提到的那样,你需要使用String.Substring的重载和一个参数来省略n - 字符并接下来。

test2 = test2.Substring(5) ' will throw an exception if the string is not long enough

答案 3 :(得分:0)

当您使用Substring并指定长度超过字符串时,它将引发异常。如果你有一个空字符串,它也会抛出异常。

但是根据你的描述,我认为你真正想要的是最后一个角色。所以你只需要做一些额外的检查:

    'check the string has something in it and is the correct length
    If Not String.IsNullOrEmpty(s) AndAlso s.Length >= 1 Then
        test2 = ""
    Else
        'get the last character of the string
        test2 = s.Substring(s.Length - 1)
    End If
相关问题