Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

vb.net - Strange TrimEnd behaviour with char

I am using TrimEnd to remove certain characters from the end of a string. Initially I thought this would work:

    Dim strNew As String = "EmployeesSickness Entitlement.rpt"
    Dim strTrim As String = "Sickness Entitlement.rpt"
    Console.WriteLine(strNew.TrimEnd(strTrim)) '<- Doesn't work

But TrimEnd only works for an array of chars or a single char string, so I tried this:

    Dim strNew As String = "EmployeesSickness Entitlement.rpt"
    Dim strTrim As String = "Sickness Entitlement.rpt"

    Dim arrChars As Char()
    ReDim arrChars(strTrim.Length)
    For i As Integer = 0 To strTrim.Length - 1
        arrChars(i) = strTrim.Substring(i, 1)
    Next

    Console.WriteLine(strNew.TrimEnd(arrChars)) '<- Employees

This works fine until I add in the slash:

    Dim strNew As String = "EmployeesSickness Entitlement.rpt"
    Dim strTrim As String = "Sickness Entitlement.rpt"

    Dim arrChars As Char()
    ReDim arrChars(strTrim.Length)
    For i As Integer = 0 To strTrim.Length - 1
        arrChars(i) = strTrim.Substring(i, 1)
    Next

    Console.WriteLine(strNew.TrimEnd(arrChars)) '<- Employ

This now outputs: Employ

Is this somehow by design? It seems strange to me. The solution to my problem is do do something like:

    If strNew.EndsWith(strTrim) Then
        Console.WriteLine(strNew.Substring(0, strNew.LastIndexOf(strTrim)))
    End If

Which is both simpler and also works, but what is happening above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Re-read the documentation of TrimEnd; you are using it wrong: TrimEnd will remove any char that is in the array from the end of the string, as long as it still finds such chars.

For example:

Dim str = "aaebbabab"
Console.WriteLine(str.TrimEnd(new Char() { "a"c, "b"c })

will output aa since it removes all trailing as and bs.

If your input looks exactly like in your example, your easiest recurse is to use Substring:

Console.WriteLine(strNew.Substring(0, strNew.Length - strTrim.Length))

Otherwise you can resort to regular expressions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...