Piyush
Piyush

Reputation: 5315

Remove only one newline from the end of string in vb.net

I have a string like below

test1
test2
test3
newline
newline
newline

here i am using s = s.TrimEnd(ControlChars.Cr, ControlChars.Lf) to remove the last newline only, but it's removing all three newline.

i want to remove only one last newline from the string if any

Thanks in advance...

Upvotes: 2

Views: 4199

Answers (4)

Piyush
Piyush

Reputation: 5315

we can do as below

Dim stringText As String() = "test1 test2 test3 newline newline newline"

Dim linesSep As String() = {vbCrLf}
Dim lines As String() = stringText.Split(linesSep, StringSplitOptions.None)
If stringText.EndsWith(vbCrLf) Then
   Dim strList As New List(Of String)
   strList.AddRange(lines)
   strList.RemoveAt(lines.Length - 1)
   lines = strList.ToArray
End If

it worked for me!!!!

Upvotes: 0

Vignesh Kumar A
Vignesh Kumar A

Reputation: 28403

Get last space and then get sub string.

Dim lastIndex = s.lastIndexOf(" ")
s = s.substring(0, lastIndex)

(Or)

Use split function

Dim s = "test1 test2 test3 newline newline newline"
Dim mySplitResult = myString.split(" ")
Dim lastWord =  mySplitResult[mySplitResult.length-1] 

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

you can try like:

if (s.EndsWith(Environment.NewLine)) {
s = s.Remove(s.LastIndexOf(Environment.NewLine)) }

Upvotes: 5

Codemunkeee
Codemunkeee

Reputation: 1613

Here you go.

s = s.substring(0, s.lastindexof(characterToBeRemoved))

Upvotes: -1

Related Questions