2014-02-17 52 views
1

僅刪除一個換行符我有一個​​像下面從字符串的結尾在vb.net

test1 
test2 
test3 
newline 
newline 
newline 

這裏我使用s = s.TrimEnd(ControlChars.Cr, ControlChars.Lf),只除去最後一個換行符的字符串,但它移除所有三個換行符。

我想如果有

在此先感謝...

回答

-1

在這裏,你去從字符串中刪除僅最後一個換行符。

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

-1這將始終刪除最後一個現有的endl。或者如果沒有endl就會中斷。我想他想要刪除最後的結局。只有當字符串以endl結尾時。 – MrPaulch

+0

但他只是想根據他給出的字符串刪除最後的endl,我的答案的想法就在那裏。如果他願意,他會成爲增加一些條件的人。 – Codemunkeee

+0

他實際上已經有了更好的代碼,可以做同樣的事情,沒有**在不存在的情況下破壞**,使用'.TrimEnd(...)',所以儘管你的論點也可以。 「他應該執行它,我給他提示」在某些情況下是有效的,因爲你給OP一個**錯誤提示,所以它不在這裏。 – MrPaulch

2

你可以嘗試這樣的:

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

+1對於最簡單直接的工作解決方案:) – MrPaulch

0

獲取最後一個空格,然後讓子字符串。

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

(OR)

使用split功能

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

我們可以做如下

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 

它爲我工作!