views:

65

answers:

4

Dear reader,

I'm faced with a bit of an issue. The scenario is that I have a multi-line text box and I want to put all that text into one single string, without any new lines in it. This is what I have at the moment:

string[] values = tbxValueList.Text.Split('\n');                
            foreach (string value in values)
            {
                if (value != "" && value != " " && value != null && value != "|")
                {
                    valueList += value;
                }
            }

The problem is that no matter what I try and what I do, there is always a new line (at least I think?) in my string, so instead of getting:

"valuevaluevalue"

I get:

"value
value
value".

I've even tried to replace with string.Replace and regex.Replace, but alas to no avail. Please advise.

Yours sincerely,
Kevin van Zanten

+7  A: 

The new line needs to be "\r\n". Better still - use Environment.NewLine.

The code is inefficient though, you are creating numerous unnecessary strings and an unnecessary array. Simply use:

tbxValueList.Text.Replace(Environment.NewLine, String.Empty);

On another note, if you ever see yourself using the += operator on a string more than a couple of times then you should probably be using a StringBuilder. This is because strings are Immutable.

David Neale
I was approaching it completely wrong then. Instead of changing the `"\n"` bit I was messing with the results. You just relieved me of that headache, thank you so much!
Kevin van Zanten
+2  A: 

Try this

tbxValueList.Text.Replace(System.Environment.NewLine, "");
Bablo
Doh! David got there before me.
Bablo
Still appreciating the help though, thanks!
Kevin van Zanten
+4  A: 

Note that new lines can be up to two characters depending on the platform.

You should replace both CR/carriage-return (ASCII 13) and LF/linefeed (ASCII 10).

I wouldn't rely on localized data as David suggests (unless that was your intention); what if you're getting the text string from a different environment, such as from a DB which came from a Windows client?

I'd use:

tbxValueList.Text.Replace((Char)13,"").Replace((Char)10,"");

That replaces all occurrences of both characters independent of order.

Christian Sciberras
Good point, I've never had reason to consider that before. +1
David Neale
I'll keep that in mind, but for the currently project it won't be necessary. Thanks though!
Kevin van Zanten
A: 

try this one as well

 string[] values = tbxValueList.Text.Replace("\r\n", " ").Split(' ');
SAK
`tbxValueList.Text.Split("\r\n", StringSplitOptions.None);` would do the same thing. That isn't what the OP was attempting to do, it was just part of his initial solution.
David Neale