1

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!

2
  • 2
    Surely you have a "Confirm" or "Submit" button somewhere? Why not build the SQL query string after the user confirms their selections? That way when it's time to submit you can simply read off the states of the check boxes directly and build the string in one go instead of removing and inserting strings every time the user changes something. Commented Dec 20, 2010 at 23:18
  • 2
    That's invalid Java. The method is called replace, not Replace. Please ensure that you post real and compileable code to avoid red herrings. Commented Dec 20, 2010 at 23:21

4 Answers 4

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

strings are immutable in java

Sign up to request clarification or add additional context in comments.

1 Comment

It's should be SQL.replace(...) not SQL.Replace(...)
1

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().

Comments

1

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.

Comments

1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.