2014-02-17 54 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 

它为我工作!