I want the following output for the following input:
input: adele
output: ae
Code:
public class delDel {
public static String delDel(String str) {
StringBuilder sb = new StringBuilder();
if(str.length() < 3){
return str;
}
else if(str.substring(1, 3).equals("del")){
StringBuilder afterRemove = sb.delete(1, 3);
return afterRemove.toString();
}
else{
return str;
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String yourStr = input.nextLine();
System.out.println(delDel(yourStr));
}
}
But I keep getting the same input.
There are multiple problems here:
StringBuilder isn't initialized with the input String. It should be StringBuilder sb = new StringBuilder(str); As such, it is always empty.substring and delete methods work with the last index exclusive, not inclusive. So to take a substring of length 3 starting at index 1, you need to call str.substring(1, 4).Corrected code:
public static String delDel(String str) {
StringBuilder sb = new StringBuilder(str);
if(str.length() < 3){
return str;
}
else if(str.substring(1, 4).equals("del")){
StringBuilder afterRemove = sb.delete(1, 4);
return afterRemove.toString();
}
else{
return str;
}
}
Side-note: since you are only using the StringBuilder in one case, you could move its declaration inside the else if (this way, you won't create a useless object when the String is less than 3 characters).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With