Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last character of a string (VB.NET 2008)

Tags:

string

vb.net

I am trying to remove a last character of a string. This last character is a newline (System.Environment.NewLine).

I have tried some things, but I can not remove it.

Example:

myString.Remove(sFP.Length - 1)

Example 2:

myString= Replace(myString, Environment.NewLine, "", myString.Length - 1)

How I can do it?

like image 974
aco Avatar asked Jan 13 '11 12:01

aco


2 Answers

If your newline is CR LF, it's actually two consecutive characters. Try your Remove call with Length - 2.

If you want to remove all "\n" and "\r" characters at the end of string, try calling TrimEnd, passing the characters:

str.TrimEnd(vbCr, vbLf)

To remove all the whitespace characters (newlines, tabs, spaces, ...) just call TrimEnd without passing anything.

like image 84
mmx Avatar answered Sep 18 '22 11:09

mmx


Dim str As String = "Test" & vbCrLf
str = str.Substring(0, str.Length - vbCrLf.Length)

the same with Environment.NewLine instead of 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)

Your remove-approach didn't work because you didn't assign the return value of this function to your original string reference:

str = str.Remove(str.Length - Environment.NewLine.Length)

or if you want to replace all NewLines:

str = str.Replace(Environment.NewLine, String.Empty)
like image 35
Tim Schmelter Avatar answered Sep 18 '22 11:09

Tim Schmelter