如何对字符串应用-=

本文关键字:应用 字符串 | 更新日期: 2023-09-27 17:51:17

我想有一个按钮,将" Text "添加到一个字符串,其中说" Test "。结果将是"TestText"。现在我按下另一个按钮,添加"Code"。所以现在字符串看起来像这样:" TestTextCode "。现在对于我的问题:我想要它,如果我再次按下第一个按钮,"Text"消失,所以只有"TestCode"会留下。我知道你可以做+=添加文本,但是否有类似的-=从字符串中删除特定的文本?

如何对字符串应用-=

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

如果您想使用-=语法,则可以使用StringBuilder,例如

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"  

没有。您需要使用String.Substring和适当的参数,或者使用String.Replace来消除这种情况。请注意,如果原始字符串已经包含Text,后者可能会变得复杂。

您最好的选择可能是将未修饰的字符串存储在字段/变量中,然后根据记录按钮状态的两个标志处理带有或不带有TextCode后缀的呈现。

如果您想要撤销,那么请保留以前的版本。字符串是不可变的,所以你还是要创建一个新的。

不直接,但是您可以使用endsWith检查是否在末尾输入,并创建一个带有子字符串

的新字符串。

没有您所描述的操作符。另一方面,您可以使用Replace函数。

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