0

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.

Kringle
  • 95
  • 1
  • 9

5 Answers5

0

you can do :

var start = two.IndexOf(one);
textbox2.text = two.Substring(start);
Noctis
  • 11,507
  • 3
  • 43
  • 82
0

You can also use Replace method

string newTwo = two.Replace(one,"");
jayvee
  • 160
  • 2
  • 17
0
If (textbox2.Text.EndsWith(textbox1.Text))
    textbox2.Text = textbox2.Text.Substring(0, textbox2.Text.Length - textbox1.Text.Length);
serdar
  • 1,564
  • 1
  • 20
  • 30
  • 1
    Cheers, didn't see that. I've always hovered my mouse over the up down arrows and it's told me my reputation isn't high enough. Just realised I could click the tick to accept the answer... – Kringle Oct 23 '14 at 06:38
0

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);
alpinsky
  • 524
  • 3
  • 7
0

@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.

Community
  • 1
  • 1
The-First-Tiger
  • 1,574
  • 11
  • 18