简体   繁体   English

删除Java字符串中的字符

[英]Removing characters in a java string

I want to remove charecters from a string. 我想从字符串中删除字符。 Example: I have an application that as the users check off the check mark its building the sql script, so if they check female it adds to the String And Gender = 'Female' . 示例:我有一个应用程序,当用户选中复选标记时,它会构建sql脚本,因此,如果他们选中female,它将添加到String And Gender = 'Female' and if they select Male it adds And Where gender = 'Male' . 如果他们选择“男性”,则会添加And Where gender = 'Male' The script is working well when adding to string as they check off but when you uncheck a item I am not sure how to remove the char that were added when it was checked. 在添加到字符串时,脚本会很好地运行,因为它们会被选中,但是当您取消选中某个项目时,我不确定如何删除在选中时添加的字符。 I tried .Replace .ReplaceAll and all the other replace. 我尝试了.Replace .ReplaceAll和所有其他替换。 I know the string I want to remove, why won't it replace it with "" . 我知道我要删除的字符串,为什么不将其替换为""

String SQL; 
SQL += " AND Gender = 'Female'";  
SQL.Replace("AND Gender = 'Female'","");

This won't work! 这行不通!

SQL = SQL.replace("AND Gender = 'Female'","");

字符串在Java中是不可变的

A java string (java.lang.String) is immutable; Java字符串(java.lang.String)是不可变的; it cannot be edited. 无法编辑。 You can try using StringBuffer (java.lang.StringBuffer) which is a mutable buffer for returning strings. 您可以尝试使用StringBuffer(java.lang.StringBuffer),它是用于返回字符串的可变缓冲区。

StringBuffer SQL = new StringBuffer();
SQL.append(" AND Gender = 'Female'");

You can also use replace and delete to remove substrings from the buffer. 您还可以使用replacedelete从缓冲区中删除子字符串。 When you're done editing the buffer simply use SQL.toString() . 完成缓冲区的编辑后,只需使用SQL.toString()

Don't use a String if you want something mutable. 如果您想要可变的东西,请不要使用字符串。 Instead you're better off using a StringBuilder object. 相反,最好使用StringBuilder对象。 Then when you're done modifying it, you can call toString() on it to get the String you need. 然后,在完成修改后,可以对其调用toString()以获取所需的String。 The API will show you the methods of this flexible class. API将向您显示该灵活类的方法。

String is immutable class. 字符串是不可变的类。 Here is another solution : convert to StringBuffer or StringBuilder and delete from the startIndex to endIndex 这是另一种解决方案:转换为StringBufferStringBuilder并将其从startIndex删除为endIndex

String s = "test tes te t ";
String str = new StringBuffer(s).delete(start, end).toString();

for example :
String str = new StringBuffer(s).delete(0, 8).toString();
System.out.println(str); // s te t 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM