开发者

How can I put text from a multi-line text box into one string?

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


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.


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.


Try this

tbxValueList.Text.Replace(System.Environment.NewLine, "");


try this one as well

 string[] values = tbxValueList.Text.Replace("\r\n", " ").Split(' ');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜