How can you trimend of textbox text from another textbox text - c#

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.

Related

Showing a string without a substring

I got a little "problem". I have these two strings (one showing the message, and the other showing the index where "##Documents##" start):
string text = currentNode.Properties["menuEntry"].Value;
string index = text.IndexOf("##Documents##").ToString();
I want to have another string for the message WITHOUT "##Documents##". Any solution to continue from the code up above, or any other solution?
For example: Message: blablabla ##Documents## 123
And what I want to show: blablabla 123
Thanks and sorry for the noobish question.
Just use the Replace() method like this:
string text = currentNode.Properties["menuEntry"].Value;
string message= text.Replace("##Documents##",string.Empty);
Just concatenate the substrings that occur before and after that substring if it is found.
int index = text.IndexOf("##Documents##");
string newText = text;
if(index > -1)
newText = text.SubString(0, index) + text.SubString(index +13);

confused about split by backslash

I am following a tutorial on internet and I have slightly changed the code for my purpose and now its not working. I have selected a path using OpenFileDialogand then tried to split selected file by backslash like below
C:\inetpub\logs\LogFiles\W3SVC1
and it always returns form1 instead file name, what am doing wrong?
string filename(string text)
{
string s = Text;
string[] arr = s.Split('\\');
string[] dot = arr[arr.Length - 1].Split('.');
return dot[0];
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
textBox1.Text = ofd.FileName;
label1.Text = filename(textBox1.Text);
}
and it always returns form1 instead file name, what am doing wrong?
You're not splitting the string text parameter at filename() method, but most likely the Text property of your Form (note that C# is case-sensitive, Text and text are completly 2 different things):
string filename(string text)
{
string s = Text;
string[] arr = s.Split('\\');
...
So change it to:
string s = text;
In addition, as suggested by others, you can use the Path.GetFileNameWithoutExtension() method which would provide you this desired logic easily:
var result = Path.GetFileNameWithoutExtension(fileName);
Your method parameter is called text but you split what you find in Text. C# is case-sensitive so Text must be a property on your Form...
By the way you can use LINQ to make your code a bit more readable. For instance you can replace arr[arr.Length - 1] by arr.Last(). Not what you asked for but a bonus tip anyway.
EDIT Yair's remark about System.IO.Path.GetFileNameWithoutExtension() is of course spot-on. Even better than doing the Split yourself and using LINQ to get the parts.
You do not need to parse it manually. You have a method to do that:
string file = Path.GetFileNameWithoutExtension(text);
C# is case-sensitive, text and Text refer to different values. In this case, you should replace:
string s = Text;
by
string s = text;
"text" being the argument passed to the filename function.

RichTextBox SelectionStart offset with linebreaks

I'm using a RichTextBox for coloured text. Let's assume I want to use different colours for different portions of the text. This is working fine so far.
I'm currently having a problem with the SelectionStart property of the RichTextBox. I've set some text to the Text property of the RichTextBox. If the text contains \r\n\r\n the SelectionStart Position won't match the position of characters with the assigned String.
Small example (WinformsApplication. Form with a RichTextBox):
public Form1()
{
InitializeComponent();
String sentence1 = "This is the first sentence.";
String sentence2 = "This is the second sentence";
String text = sentence1 + "\r\n\r\n" + sentence2;
int start1 = text.IndexOf(sentence1);
int start2 = text.IndexOf(sentence2);
this.richTextBox1.Text = text;
String subString1 = text.Substring(start1, sentence1.Length);
String subString2 = text.Substring(start2, sentence2.Length);
bool match1 = (sentence1 == subString1); // true
bool match2 = (sentence2 == subString2); // true
this.richTextBox1.SelectionStart = start1;
this.richTextBox1.SelectionLength = sentence1.Length;
this.richTextBox1.SelectionColor = Color.Red;
this.richTextBox1.SelectionStart = start2;
this.richTextBox1.SelectionLength = sentence2.Length;
this.richTextBox1.SelectionColor = Color.Blue;
}
The RichTextBox looks like this:
As you can see, the first two characters of the second sentence are not coloured. This is the result of an offset produced by \r\n\r\n.
What is the reason for this? Should I use another control for colouring text?
How do I fix the problem in a reliable way? I've tried replacing the "\r\n\r\n"with a String.Empty, but that produces other offset problem.
Related question:
Inconsistent behaviour between in RichTextBox.Select with SubString method
It seems that the sequence \r\n counts for one character only when doing selections. You can do the measurements in a copy of the string where all \r\n are replaced by \n.
Just for completeness (I'll stick to linepogls answer for now):
I've found another way to get indices for the SelectionStart property. The RichTextBox offers a Find method, that can be used to retrieve index positions based on a specified string.
Be aware of the fact, that the text you want to highlight might not be unique and occur multiple times. You can use an overload to specify a start position for the search.

Limit of characters in string

I have the textbox that takes some string. This string could be very long. I want to limit displayed text (for example to 10 characters) and attach 3 dots like:
if text box takes value "To be, or not to be, that is the question:" it display only "To be, or..."
Or
if text box takes value "To be" it display "To be"
Html.DevExpress().TextBox(
tbsettings =>
{
tbsettings.Name = "tbNameEdit";;
tbsettings.Width = 400;
tbsettings.Properties.DisplayFormatString=???
}).Bind(DataBinder.Eval(product, "ReportName")).GetHtml();
You should use a Label control to display the data. Set AutoSize to false and AutoEllipsis to true. There are good reasons why a TextBox does not have this functionality, among which:
where are you going to store the truncated data?
if the user selects the text to edit or even copy, how do you handle that?
If you counter-argument is that the TextBox is read-only, then that is only more reason to re-think the control you are using for this.
If you need to use a regex, you can do this:
Regex.Replace(input, "(?<=^.{10}).*", "...");
This replaces any text after the tenth character with three dots.
The (?<=expr) is a lookbehind. It means that expr must be matched (but not consumed) in order for the rest of the match to be successful. If there are fewer than ten characters in the input, no replacement is performed.
Here is a demo on ideone.
Try this:
string displayValue = !string.IsNullOrWhiteSpace(textBox.Text) && textBox.Text.Length > 10
? textBox.Text.Left(10) + "..."
: textBox.Text;
In an extension method:
public static string Ellipsis(this string str, int TotalWidth, string Ellipsis = "...")
{
string output = "";
if (!string.IsNullOrWhiteSpace(str) && str.Length > TotalWidth)
{
output = output.Left(TotalWidth) + Ellipsis;
}
return output;
}
Using it would be:
string displayValue = textBox.Text.Ellipsis(10);
string textToDisplay = (inputText.Length <= 10)
? inputText
: inputText.Substring(0, 10) + "...";
Something like this?
static void SetTextWithLimit(this TextBox textBox, string text, int limit)
{
if (text.Length > limit)
{
text = text.SubString(0, limit) + "...";
}
textBox.Text = text;
}
Show what you have tried and where you are stuck.
You don't need to use regex
string s = "To be, or not to be, that is the question:";
s = s.Length > 10 ? s.Remove(10, s.Length - 10) + "..." : s;
string maxStringLength = 10;
string displayStr = "A very very long string that you want to shorten";
if (displayStr.Length >= maxStringLength) {
displayStr = displayStr.Substring(0, maxStringLength) + " ...";
}
//displayStr = "A very very long str ..."

Clipboard can copy a few words?

I'm weak in English so I hope you will understand this.
I learned yesterday that Clipboard is copy.
//textBox1.Text = "My name is not exciting";
Clipboard.SetText(textBox1.Text);
textBox2.Text = Clipboard.GetText();
This code copies your everything from the textbox1 and paste it in textbox2 right?
So it's possible to copy only a few words from textbox1 and paste it in textbox2?
If you don't understand, I'm want copy only a few words not all the line.
Even if this high level code still bring me :)
Clipboard.GetText(); will return the raw copied elements.
What you can do is save them to some variable:
string text = Clipboard().GetText();
Then do something with text, to get the elements you need:
textBox2.Text = text.Substring(0, 10); // An example.
The main idea to take away from this is, GetText() will give you a string. It's up to you to slice and dice that string any way you see fit and then make use of the results.
You don't need the Clipboard for this. Your user won't like that ;)
Just create a variable like this:
string box1Content = textBox1.Text;
textBox2.Text = boxContent;
You can even skip that variable.
If you really want to use the clipboard, your way is doing that.
For just getting some text out of the textbox you can either use substring or regular expressions.
http://msdn.microsoft.com/en-us/library/aka44szs.aspx
Good luck
Daniel, the substring method is a good one to use. You simply tell it where you want to take a piece of your text and it will create a new string of just that.
textBox1.Text = "MY name is not exciting";
//pretend you only want "not exciting" to show
int index = textBox1.Text.IndexOf("not");//get the index of where "not" shows up so you can cut away starting on that word.
string partofText = textBox1.Text.Substring(index);//substring uses the index (in this case, index of "not") to take a piece of the text.
Clipboard.SetText(partofText);
textBox2.Text = Clipboard.GetText();
To my mind is better idea to take selected text from text box.
I'm not sure witch kind of text box you are using but so show example on WPF you should use TextBox.SelectedText property.
I like linq. :-)
This is a example for splitting the string, enumerable it and concats in one:
textBox1.Text = "My name is not exciting";
int firstWord = 2;
int lastWord = 4;
string[] wordList = textBox1.Text.Split(new[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
string newText = string.Concat(wordList.Where((word, count) => count >= firstWord - 1 && count < lastWord).Select(w => w + " ")).TrimEnd();
Clipboard.SetText(newText);
textBox2.Text = Clipboard.GetText();
// Result: "name is not"
Edit: and without Clipboard you can use simply this Line
textBox2.Text = newText;

Categories