vb.net 从字符串中修剪最后 4 个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1338743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trim last 4 characters from string?
提问by Rob Farley
How can I trim MyString to be MyStr?
如何将 MyString 修剪为 MyStr?
Thanks, google failed again :(
谢谢,谷歌又失败了:(
回答by Rob Farley
YourString.Left(YourString.Length-4)
or:
或者:
YourString.Substring(0,YourString.Length-4)
回答by JaredPar
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
Rob 的回答大部分是正确的,但是只要字符串中的字符少于 4 个,SubString 解决方案就会失败。如果长度超过字符串的末尾,将抛出异常。以下解决了该问题
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
回答by shahkalpesh
c#
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)
vb.net(带有 VB6 风格的函数)
dim str as string = "MyString"
Console.WriteLine(Mid(str, 1, len(str) - 3))
回答by H.A. Sanger
This is what I used in my program (VB.NET):
这是我在我的程序(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.
这是我的第一个答案。希望它可以帮助某人。如果您不喜欢这个答案,请随意投反对票。