How to delete a substring between specific characters in Java?

1118 views java

First of all, sorry if code looks messy. I have to make a To do list on Java where the user can add and delete chores, without using regex. I can only use methods from the String class. Every chore entered should end with "\n":

list = list + addedChore + "\n"

If user wants to delete the first chore for example:

endofChore1 = list.indexOf("\n", 0);
chore1 = list.substring(0, endofChore1);
chore1 = ""; 

What i tried to do was to get the index of the first \n and make it a substring starting from index 0 to the index of the first \n, and finally replace that substring with an empty string that way it deletes the chore from the list. However, it is not working. What can I do to fix this? Thank you.

answered question

Where is the rest of your code? Also, note that you extracted part of the list, leaving the list exactly as it was before. Then you assign the variable you extracted that part to a new value, so you've now a) not touched list and b) made the chore1 = list.... instruction a noop.

@babyprog Strings are immutable

1 Answer


Strings are immutable.


chore1 = list.substring(0, endofChore1);
chore1 = ""; 


list = list.substring(endofChore1);

Here is your full code:-

public static void main(String[] args) {
    String list = "choreA\nchoreB\n";
    int endofChore1 = list.indexOf("\n", 0);
    list = list.substring(endofChore1);

PS - Not trying to come up with the best logic, just fixing the current issue the OP is having with their code.

posted this

Have an answer?


Please login first before posting an answer.