user1924391
user1924391

Reputation: 255

NewLine replacement c#?

I have a windows phone application. In the application I have a textbox whose acceptsreturn property is set to true.

What I want to do is create a string from the textbox and replace the new lines with a specific character, something like "NL"

I've tried the following but none of them worked.

string myString = myTextBox.Text.Replace(Environment.NewLine,"NL");
string myString = myTextBox.Text.Replace("\n","NL");

Upvotes: 6

Views: 1980

Answers (4)

Alex Filipovici
Alex Filipovici

Reputation: 32561

A question with a similar topic had a quite elegant answer you might consider interesting to use:

using System.Text.RegularExpressions;

myTextBox.Text = Regex.Replace(myTextBox.Text, @"\r(?!\n)|(?<!\r)\n", "NL");

Upvotes: 0

user1968030
user1968030

Reputation:

Use this code

var myString = myTextBox.Text.Replace("\r","NL");

This is for compatibility with every operating systems.

Upvotes: 1

Rab
Rab

Reputation: 35572

Consider replacing different types of line breaks to handle all the possibilities

string myString myTextBox.Replace("\r\n", "NL").Replace("\n", "NL").Replace("\r", "NL");

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460108

I'm not familiar with windows phone(or silverlight), but try to split with \r instead:

string myString = myTextBox.Text.Replace("\r","NL");

Why does a Silverlight TextBox use \r for a newline instead of Environment.Newline (\r\n)?

Upvotes: 7

Related Questions