c# replace "\n" text with newline in a textbox - c#

I have some text (for example "o\nour first place, and this\n\n13") and I want that for each "\n" string founded into the text this must be replaced with newline...
output for the example will be:
o
our first place, and this
13
How can I make? textbox is multiline
the code is
string text_str = txtbox.Text;
text_str .Replace("(?<!\r)\n", "\r\n");
txtbox.Clear();
txtbox.Text = text_str;

I think you're looking for something like this:
string text_str = txtbox.Text;
text_str = text_str.Replace("\\n", "\r\n");
txtbox.Clear();
txtbox.Text = text_str;
Although that's a really round about way of doing things. This will accomplish the same thing:
txtbox.Text = txtbox.Text.Replace("\\n", "\r\n");

Here you are:
string text_str = "o\nour first place, and this\n\n13";
text_str = text_str.Replace("\n", "\r\n");
Hope this help.

This should work:
txtbox.Text = txtbox.Text.Replace("\\n", Environment.NewLine);

Note very sure what the OP needed, but in case someone else comes here looking for what I was:
blah.Text = Regex.Replace(origString, "(?<!\\r)\\n", "\\r\\n")

Related

How to paste formatted text in textbox, C#

am trying to paste some emails into a large textbox with a semi-colon(;) at the end of each email but i don't want the semi-colon to be at the back of the last email. Please how can i go about this, all answers would be welcomed.
You can use the TrimEnd() function
string Emails = "me#email.com;metoo#email.com;";
this.textBox1.Text = Emails.TrimEnd(';');
or if it's already in your TextBox
this.textBox1.Text = this.textBox1.Text.TrimEnd(';');
Try this
string email = "metoo#email.com;abc#email.com;xyz#email.com;";
this.textBox1.text = email.Replace(";", string.Empty);
//to show emails in separate lines then use it in this way
this.textBox1.text = email.TrimEnd(';').Replace(";", Environment.NewLine);
Just remove the last char. You can do that with a substring.
I don't understand what do you want. But maybe this code can help you to remove the last semi-colon if it exists.
var str = "email#email.com;email2#email.com;email3#email.com;";
var length = str.Length - 1;
if (str.LastIndexOf(';') == length)
{
str.Remove(length);
}

How can you trimend of textbox text from another textbox text

I have two textbox's textbox1 (read/write) & textbox2 (read only), textbox1 is where you enter text at which point you press a button to pass that text into textbox2 (textbox2 continually concatenates the text from textbox1). I have a second button that I want to press to remove the text from textbox2 that is still in textbox1. Can anyone suggest how to do this?
I was thinking;
string one = textbox1.text;
string two = textbox2.text;
string newTwo = two.trimend( value of string 'one' needs to be removed );
textbox2.text = newTwo;
textbox1;
world
textbox2;
hello world
I know this sounds odd but it's a bit of a work around for an algebra calculator.
If (textbox2.Text.EndsWith(textbox1.Text))
textbox2.Text = textbox2.Text.Substring(0, textbox2.Text.Length - textbox1.Text.Length);
you can do :
var start = two.IndexOf(one);
textbox2.text = two.Substring(start);
You can also use Replace method
string newTwo = two.Replace(one,"");
As far as i undestand your question boils down to "How to implement TrimEnd?". You can use code like this:
public static class StringExtensions
{
public static string TrimEnd(this string str,
string subject,
StringComparison stringComparison)
{
var lastIndexOfSubject = str.LastIndexOf(subject, stringComparison);
return (lastIndexOfSubject == -1
|| (str.Length - lastIndexOfSubject) > subject.Length)
? str
: str.Substring(0, lastIndexOfSubject);
}
}
Then is your code-behind:
textbox2.text = textbox2.text.TrimEnd(textbox1.text, StringComparison.CurrentCulture);
#jayvee is right. Replacing with string.Empty would do.
But there's one problem with that:
When replacing "Hello" in "Hello World" the leading whitespace would remain. newTwo would be " World". You may also would want to replace multiple whitespaces via Regex as posted here and then Trim() the new string.
Also this is case sensitive.

Parse text from textbox

i have string in textbox:
`New-Value = 12,34 -- Old-Values: 12,31,`
what i'd like to do is to get Old-Value so "12,31,"
How can i get from this textbox this specific information do this? So value is between ":" and ","
Tnx
Regex.Match("New-Value = 12,34 -- Old-Values: 12,31,",#"\:(.+)\,").Groups[1].Value.Trim()
const string oldPointer = "Old-Values: ";
var text = "New-Value = 12,34 -- Old-Values: 12,31,";
var old = text.Substring(text.IndexOf(oldPointer) + oldPointer.Length).TrimEnd(',');
Not very clear if this is a fixed (static) format of your string, but by the way:
A simple solution could be:
string str = "New-Value = 12,34 -- Old-Values: 12,31,";
str.Substring(str.IndexOf(':') + 1);
More complex one should involve Regular expressions, like an answer of L.B or others if any.

Add spacing to textbox results

Hi there I have the following code-
richTextBox1.Text = richTextBox1.Text + action + "ok: " + ok.ToString();
richTextBox1.Text = richTextBox1.Text + "err: " + err.ToString();
richTextBox1.Text = richTextBox1.Text + "\r\n";
textBox1.Text = textBox1.Text;
The results look like -
ok:7err:0
But I want-
ok:7
err:0
With spacing, to make it look better how can I do this?
You could add another 2 lines:
richTextBox1.Text += Environment.NewLine;
richTextBox1.Text += Environment.NewLine;
between your "ok" and "err" - assuming you want a blank line between the two lines of output. However, you should either be using string.Format or a StringBuilder to create your output as concatenating strings this way in inefficient.
You also don't need the final:
textBox1.Text = textBox1.Text;
as that is just setting the text box contents back to itself and does nothing.
You've already got your answer, you just have it in the wrong place! The key is to use the escape sequence \r\n, which inserts a carriage return and a new line.
Also, there's no reason to split this code up into multiple lines. You end up incurring a performance penalty for doing so. It's better to do all of the string concatenation at one time. (You aren't doing enough concatenations here to justify using the StringBuilder class, but it's worth keeping in mind that strings are immutable in .NET and writing code accordingly.)
Try rewriting the code like this:
textBox1.Text = textBox1.Text + action + "ok: " + ok.ToString(); + "\r\n" +
"err: " + err.ToString(); + "\r\n";
You can also complete eliminate the last line of code, as that simply sets the value of textBox1.Text to itself. It's a no-op, meaning that it does nothing at all.
first that you could do all these in a single statement, second you could use += operator instead, and third what is that last statement doing?! it not needed, fourth add "\n" after each part you need there is no limit where you should put it, no "\r" needed.

How to insert newline in string literal?

In .NET I can provide both \r or \n string literals, but there is a way to insert
something like "new line" special character like Environment.NewLine static property?
Well, simple options are:
string.Format:
string x = string.Format("first line{0}second line", Environment.NewLine);
String concatenation:
string x = "first line" + Environment.NewLine + "second line";
String interpolation (in C#6 and above):
string x = $"first line{Environment.NewLine}second line";
You could also use \n everywhere, and replace:
string x = "first line\nsecond line\nthird line".Replace("\n",
Environment.NewLine);
Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.
If you want a const string that contains Environment.NewLine in it you can do something like this:
const string stringWithNewLine =
#"first line
second line
third line";
EDIT
Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:
As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
One more way of convenient placement of Environment.NewLine in format string.
The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine
Usage
" X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
gives:
X=1
Y=2
X+Y=3
Code
///<summary>
/// Use "string".FormatIt(...) instead of string.Format("string, ...)
/// Use {nl} in text to insert Environment.NewLine
///</summary>
///<exception cref="ArgumentNullException">If format is null</exception>
[StringFormatMethod("format")]
public static string FormatIt(this string format, params object[] args)
{
if (format == null) throw new ArgumentNullException("format");
return string.Format(format.Replace("{nl}", Environment.NewLine), args);
}
Note
If you want ReSharper to highlight your parameters, add attribute to the method above
[StringFormatMethod("format")]
This implementation is obviously less efficient than just String.Format
Maybe one, who interested in this question would be interested in the next question too:
Named string formatting in C#
string myText =
#"<div class=""firstLine""></div>
<div class=""secondLine""></div>
<div class=""thirdLine""></div>";
that's not it:
string myText =
#"<div class=\"firstLine\"></div>
<div class=\"secondLine\"></div>
<div class=\"thirdLine\"></div>";
If you really want the New Line string as a constant, then you can do this:
public readonly string myVar = Environment.NewLine;
The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.
static class MyClass
{
public const string NewLine="\n";
}
string x = "first line" + MyClass.NewLine + "second line"
newer .net versions allow you to use $ in front of the literal which allows you to use variables inside like follows:
var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";
If you are working with Web application you can try this.
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")
If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -
string s1 = comboBox1.Text; // s1 is the variable assigned to box 1, etc.
string s2 = comboBox2.Text;
string both = s1 + "\r\n" + s2;
textBox1.Text = both;
A typical answer could be s1
s2 in the text box using defined type style.
I like more the "pythonic way"
List<string> lines = new List<string> {
"line1",
"line2",
String.Format("{0} - {1} | {2}",
someVar,
othervar,
thirdVar
)
};
if(foo)
lines.Add("line3");
return String.Join(Environment.NewLine, lines);
Here, Environment.NewLine doesn't worked.
I put a "<br/>" in a string and worked.
Ex:
ltrYourLiteral.Text = "First line.<br/>Second Line.";

Categories