How can I trim MyString to be MyStr?
Thanks, google failed again :(
Rob's answer is mostly correct but the SubString solution will fail whenever the string has less than 4 characters in it. If the length goes past the end of the string an exception will be thrown. The following fixes that issue
Public Function TrimRight4Characters(ByVal str As String) As String
If 4 > str.Length Then
return str.SubString(4, str.Length-4)
Else
return str
End if
End Function
YourString.Left(YourString.Length-4)
or:
YourString.Substring(0,YourString.Length-4)
This is what I used in my program (VB.NET):
Public Function TrimStr(str As String, charsToRemove As String)
If str.EndsWith(charsToRemove) Then
Return str.Substring(0, str.Length - charsToRemove.Length)
Else
Return str
End If
End Function
Usage:
Dim myStr As String = "hello world"
myStr = TrimStr(myStr, " world")
This is my first answer. Hope it helps someone. Feel free to downvote if you don't like this answer.
c#
string str = "MyString";
Console.WriteLine(str.Substring(0, str.Length - 3));
vb.net
dim str as string = "MyString"
Console.WriteLine(str.Substring(0, str.Length - 3))
vb.net (with VB6 style functions)
dim str as string = "MyString"
Console.WriteLine(Mid(str, 1, len(str) - 3))