string 删除字符串的最后一个字符 (VB.NET 2008)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4680024/
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
Remove last character of a string (VB.NET 2008)
提问by aco
I am trying to remove a last character of a string. This last character is a newline (System.Environment.NewLine).
我正在尝试删除字符串的最后一个字符。最后一个字符是换行符 (System.Environment.NewLine)。
I have tried some things, but I can not remove it.
我尝试了一些东西,但我无法删除它。
Example:
例子:
myString.Remove(sFP.Length - 1)
Example 2:
示例 2:
myString= Replace(myString, Environment.NewLine, "", myString.Length - 1)
How I can do it?
我该怎么做?
回答by Mehrdad Afshari
If your newline is CR LF, it's actually two consecutive characters. Try your Remove
call with Length - 2
.
如果你的换行符是 CR LF,它实际上是两个连续的字符。试试你的Remove
电话Length - 2
。
If you want to remove all "\n" and "\r" characters at the end of string, try calling TrimEnd
, passing the characters:
如果要删除字符串末尾的所有 "\n" 和 "\r" 字符,请尝试调用TrimEnd
,传递字符:
str.TrimEnd(vbCr, vbLf)
To remove all the whitespace characters (newlines, tabs, spaces, ...) just call TrimEnd
without passing anything.
要删除所有空白字符(换行符、制表符、空格等),只需调用TrimEnd
而不传递任何内容。
回答by Tim Schmelter
Dim str As String = "Test" & vbCrLf
str = str.Substring(0, str.Length - vbCrLf.Length)
the same with Environment.NewLine instead of vbCrlf:
与 Environment.NewLine 而不是 vbCrlf 相同:
str = "Test" & Environment.NewLine
str = str.Substring(0, str.Length - Environment.NewLine.Length)
Btw, the difference is: Environment.NewLine is platform-specific(f.e. returns other string in other OS)
顺便说一句,不同之处在于:Environment.NewLine 是特定于平台的(fe 返回其他操作系统中的其他字符串)
Your remove
-approach didn't work because you didn't assign the return value of this function to your original string reference:
您的remove
-approach 不起作用,因为您没有将此函数的返回值分配给原始字符串引用:
str = str.Remove(str.Length - Environment.NewLine.Length)
or if you want to replace all NewLines:
或者如果你想替换所有的 NewLines:
str = str.Replace(Environment.NewLine, String.Empty)
回答by Jay Ponkia
Use:
用:
Dim str As String
str = "cars,cars,cars"
str = str.Remove(str.LastIndexOf(","))