Reputation: 9408
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'
. and if they select Male it adds 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. 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!
Upvotes: 1
Views: 776
Reputation:
String is immutable class. Here is another solution : convert to StringBuffer or StringBuilder and delete from the startIndex to 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
Upvotes: 1
Reputation: 30141
SQL = SQL.replace("AND Gender = 'Female'","");
strings are immutable in java
Upvotes: 7
Reputation: 285460
Don't use a String if you want something mutable. Instead you're better off using a StringBuilder object. Then when you're done modifying it, you can call toString() on it to get the String you need. The API will show you the methods of this flexible class.
Upvotes: 1
Reputation: 290
A java string (java.lang.String) is immutable; it cannot be edited. You can try using StringBuffer (java.lang.StringBuffer) which is a mutable buffer for returning strings.
StringBuffer SQL = new StringBuffer();
SQL.append(" AND Gender = 'Female'");
You can also use replace
and delete
to remove substrings from the buffer. When you're done editing the buffer simply use SQL.toString()
.
Upvotes: 1