babyprog
babyprog

Reputation: 11

How to delete a substring between specific characters in 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.

Edit: This is what i wrote to delete any given chore. I don't see what's wrong with it.

int choreToDelete;   // number associated with chore user wants to delete
int begin = 0;
int i = 0;
int end;
String stringToDelete;


  if (choreToDelete >= 1 && choreToDelete <= numberOfChores){
   while (i < choreToDelete - 1) {
     end = list.indexOf("\n", begin);
     begin = end;
     i = i + 1;
   }
  }
stringToDelete = list.indexOf("\n", begin);
list = list.substring(stringToDelete);

Upvotes: 1

Views: 84

Answers (1)

Kartik
Kartik

Reputation: 7917

Strings are immutable.

Replace

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

with

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);
    System.out.println(list);
}

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

Edit:

Since you have shown effort of making a generic delete method, here is the full code. It handles cases like if choreToDelete is less than 1 and if it is more than the number of chores.

public static void main(String[] args) {
    String list = "choreA\nchoreB\nchoreC\n";
    list = deleteChore(list, 2);
    System.out.println(list);
}

private static String deleteChore(String list, int choreToDelete) {
    if (choreToDelete < 1 || choreToDelete > list.split("\n").length) return list;
    if (choreToDelete == 1) return list.substring(list.indexOf("\n") + 1);
    if (!list.endsWith("\n")) list = list + "\n";
    int startIndexOfChoreToDelete = nthIndexOf(list, "\n", choreToDelete - 1);
    int endIndexOfChoreToDelete = nthIndexOf(list, "\n", choreToDelete);
    return list.substring(0, startIndexOfChoreToDelete) + list.substring(endIndexOfChoreToDelete);
}

private static int nthIndexOf(String str, String substr, int n) {
    int pos = str.indexOf(substr);
    while (--n > 0 && pos != -1)
        pos = str.indexOf(substr, pos + 1);
    return pos;
}

Upvotes: 1

Related Questions