Criel
Criel

Reputation: 815

How to tell if carriage return is in my string?

I have a textbox control that allows for the user of enter button to enter details like ADdresses or other demographic information. Since the default for addresses are as follows:

Address 1
Address 2
City, st
Zip

I am wondering if there is a way to tell if the Enter key was used to make a new line here? I've looked around and currently the only is to have a check in VB for vbCrLf however I'm not seeing it pick this up in the code.

Test data for this would be something similar to below

123 N Street
S Test Street
Test City, XX
91883

The code below is what I'm trying to just replace any return carriage and replace with a space

Text.Replace(vbCrLf, " ")

Will this vbCrLf not pick up a carriage return unless there's an actual space between the above test values?

Upvotes: 0

Views: 10457

Answers (4)

OSKM
OSKM

Reputation: 728

I spent quite some time to resolve exactly this problem, the solution I came across was:

text = text.Replace(" ", ControlChars.CrLf)

Sorry cant remember where I found the solution but if I do remember it I will post the link here.

Upvotes: 2

Steve
Steve

Reputation: 216313

If you are using a MultiLine textbox (as it seems from your sample) then you don't need to search for the newline characters and replace them with a space.

You could simply use the Lines property where every line is stored separated from the other and then use the string Join method to create a single line string

Dim singleLine = string.Join(" ", myTextBox.Lines)

Of course if you are just interested to know if there is a newline character then just check the Length property of the Lines array

Upvotes: 4

SeraM
SeraM

Reputation: 487

vbCrLf actually refers to two characters, a carriage return (13) and a line feed (10).

I would search and replace each separately. It isn't strictly necessary (as replace will work on the two characters at once), but can catch instances in which the user cut and pasted information, instead of typing directly into the text box.

Text = Text.Replace(vbCr, " ")
Text = Text.Replace(vbLf, " ")

or

Text = Text.Replace(vbCr, " ").Replace(vbLf, " ")

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.constants.vbcrlf(v=vs.110).aspx

Upvotes: 3

user700390
user700390

Reputation: 2339

The Replace() function will indeed properly detect and replace all occurrences of the target with the replacement - it does not matter whether there are leading or trailing spaces.

However, please consider that String objects are immutable and cannot be changed after they have been instantiated. Therefore, Replace() does not modify the existing object but rather returns a new string as its result.

To actually see the results of the function call, you need to do something along these lines:

newString = Text.Replace(vbCrLf, " ")

Upvotes: 2

Related Questions