Remove carriage return from string
I would like to insert the following into a string
<p>some text here</p>
<p>some text here</p>
<p>some text here</p>
I want it to go into a s开发者_运维技巧tring as follows
<p>some text here</p><p>some text here</p><p>some text here</p>
i.e. without the carriage returns.
How do I achieve this?
Since you're using VB.NET, you'll need the following code:
Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")
You could use escape characters (\r
and \n
) in C#, but these won't work in VB.NET. You have to use the equivalent constants (vbCr
and vbLf
) instead.
How about:
string s = orig.Replace("\n","").Replace("\r","");
which should handle the common line-endings.
Alternatively, if you have that string hard-coded or are assembling it at runtime - just don't add the newlines in the first place.
If you want to remove spaces at the beginning/end of a line too(common when shortening html) you can try:
string.Join("",input.Split('\n','\r').Select(s=>s.Trim()))
Else use the simple Replace
Marc suggested.
In VB.NET there's a vbCrLf constant for linebreaks:
Dim s As String = "your string".Replace(vbCrLf, "")
Assign your string to a variable and then replace the line break and carriage return characters with nothing, like this:
myString = myString.Replace(vbCrLf, "")
You can also try:
string res = string.Join("", sample.Split(Environment.NewLine.ToCharArray())
Environment.NewLine should make it independent of platform.
Recommended Read:
Environment.NewLine Property
How about using a Regex?
var result = Regex.Replace(input, "\r\n", String.Empty)
If you just want to remove the new line at the very end use this
var result = Regex.Replace(input, "\r\n$", String.Empty)
For VB.net
vbcrlf = environment.newline...
Dim MyString As String = "This is a Test" & Environment.NewLine & " This is the second line!"
Dim MyNewString As String = MyString.Replace(Environment.NewLine,String.Empty)
Microsoft helped me on this one. I have a TextBox that I enter info into, when I hit Enter it transfers that info to another TextBox. The first TextBox has a CrLf which interfered with it's look. With this e.Handled, no CrLf. Hope it helps. I failed to say, VB.NET and WinForms. https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress?view=windowsdesktop-6.0
Private nonNumberEntered As Boolean = False
Private Sub TxtBxGetString_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBxGetString.KeyPress
TxtBxReversed.Text = ""
If Asc(e.KeyChar) = 13 Then
If nonNumberEntered = False Then
e.Handled = True
End If
str = TxtBxGetString.Text
TxtBxReversed.Text = str
TxtBxLength.Text = Len(str)
TxtBxLength.Focus()
End If
End Sub
I just had the same issue in my code today and tried which worked like a charm.
.Replace("\r\n")
精彩评论