Tim Kathete Stadler
Tim Kathete Stadler

Reputation: 1069

How to apply -= to a string?

I want to have a button which adds "Text" to a string which says "Test". The outcome would be "TestText". Now I press a another button which adds "Code". So now the string looks like this: "TestTextCode". Now for my problem: I want it so that if I press the first Button again, the "Text" dissapears, so only "TestCode" would be left. I know you can do += do add text, but is there something similiar like -= to delete specific text from a string?

Upvotes: 0

Views: 5426

Answers (6)

Tim Schmelter
Tim Schmelter

Reputation: 460068

You can use a StringBuilder if you want to use -= syntax, f.e.

string textString = "Text";
string codeString = "Code";

var textBuilder = new StringBuilder("Test"); // "Test"
// simulate the text-button-click:
textBuilder.Append(textString); // "TestText"  
// simulate the code-button-click:
textBuilder.Append(codeString); // "TestTextCode"  
// simulate the remove-text-button-click:
textBuilder.Length -= textString.Length; // "TestText"  
// simulate the remove-code-button-click:
textBuilder.Length -= codeString.Length; // "Test"  

Demo

Upvotes: 3

CuccoChaser
CuccoChaser

Reputation: 1079

string test = "";
test = test.Replace("Text", "");

Upvotes: 10

daryal
daryal

Reputation: 14919

there is no operator on string like you have described. On the otherhand, you can use Replace function.

string s = "TestTextCode";
s = s.Replace("Text", "");

Upvotes: 0

rekire
rekire

Reputation: 47945

Not directly, but you could check with endsWith if the input in at the end and create a new string with substring

Upvotes: 0

Agent_L
Agent_L

Reputation: 5411

If you want an undo, then keep previous version. Strings are immutable, so you're creating new one anyway.

Upvotes: 0

David M
David M

Reputation: 72860

No there isn't. You'd need to either use String.Substring with appropriate parameters, or String.Replace to cut this out. Note that the latter may get complicated if the original string already contains Text.

Your best bet is probably to store the unadorned string in a field/variable, and then just deal with rendering it with or without the Text and Code suffixes according to two flags recording the button states.

Upvotes: 0

Related Questions