Reputation: 2046
I'm wondering if there is any way to subtract Strings that are contained within another String in Java based on the selection of a user.
This is the code that I have:
removeIng = pH1 + pH2 + pH3;
System.out.print("Enter number corresponding to element you want to remove");
System.out.printf("%s",removeIng);
remove = in.nextInt();
switch(remove)
{
case 1:
removeIng = pH2 + pH3;
case 2:
removeIng = pH1 + pH3;
case 3:
removeIng = pH1 + pH2;
}
I need the code to be dynamic so that the user could possibly remove all the elements if they want. I have an outside loop already created to allow for that possibility. But I'm at a loss as to how to have "removeIng" subtract the user selected element. I can figure out the other part. Any help would be greatly appreciated. I've found ways to subtract strings that are declared as "blah blah" but nothing like this. Hopefully that makes sense.
Thanks.
Upvotes: 1
Views: 845
Reputation: 30828
Based on your sample code, it might be easier to keep track of which bits of the string the user doesn't want, and generate removeIng
based on that. Here's some pseudocode. I sacrificed optimization in favor of clarity:
String[] components;
// what used to be called pH1 is accessed by components[0];
boolean[] deletedPieces;
// initially set to all false
// contains true for segments that the user wants to delete, false otherwise
your outer loop here {
// ask the user which piece to delete here
remove = in.nextInt() - 1; // - 1 to account for array indices starting at 0
deletedPieces[remove] = true;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < total number of possible pieces; i++) {
if(deletedPieces[i])
// user wanted this piece deleted; do nothing
else
sb.append(components[i]);
}
removeIng = sb.toString();
}
Upvotes: 0
Reputation: 6396
Try String.replace(CharSequence target, CharSequence replacement)
(javadoc). There is also a version of this method that uses regular expressions, if you need a more powerful replacement syntax.
Upvotes: 1