I'm trying to implement a function able to remove some substrings from a given string using their starting and ending offset. I've got an ArrayList of objects like this:
"This","0","4"
"This is","0","8"
"some","39","43"
Here my class:
package com.giacomomarangoni;
import java.io.IOException;
import java.util.ArrayList;
public class GNTestClass {
private static String removeSubFromString(String line,int start,int end, int decrement){
/* DECREMENT BASED ON SUBSTRING REMOVED */
start = start - decrement;
end = end - decrement;
retu line.substring(0,start)+line.substring(end);
}
private static ArrayList<GNEntityObject> populateArrayList(){
ArrayList<GNEntityObject> entities = new ArrayList<>();
GNEntityObject e1 = new GNEntityObject();
e1.setWord("This");
e1.setStartOffset(0);
e1.setEndOffset(4);
entities.add(e1);
/* START COMMENT HERE TO REMOVE OVERLAPPING */
GNEntityObject e2 = new GNEntityObject();
e2.setWord("This is");
e2.setStartOffset(0);
e2.setEndOffset(8);
entities.add(e2);
/* END COMMENT */
GNEntityObject e3 = new GNEntityObject();
e3.setWord("some");
e3.setStartOffset(39);
e3.setEndOffset(43);
entities.add(e3);
retu entities;
}
public static void main(String[] args) throws IOException {
ArrayList<GNEntityObject> entities = populateArrayList();
String testString = "This is a text, I would like to remove some string in the right way";
int dec = 0;
for (GNEntityObject e : entities){
testString = removeSubFromString(testString, e.getStartOffset(), e.getEndOffset(), dec);
/* UPDATE DECREMENT BASED ON SUBSTRING LENGTH */
dec += (e.getEndOffset() - e.getStartOffset());
}
System.out.println(testString);
}
}
if substrings are not overlapped everything works, otherwise they don't. I know why, but I'm not able to overcame this particular case. Hope someone will help. Thank you.
