I am trying to trim a string to the first occurrence of a specific word in a single string of comma separated words. E.g.:
deleteLastOccurrence("foo,bar,dog,cat,dog,bird","dog")
should return
"foo,bar,dog"
I have the following, and it doesn’t seem to be working correctly:
public String deleteLastOccurrence(String original, String target){
String[] arr = original.split(",");
arr = Arrays.copyOfRange(arr, Arrays.asList(arr).indexOf(target), original.length()-1);
path = StringUtils.join(pathArray,",");
}
Any suggestions on a simpler method? Thanks in advance…
Use regex replace:
This code also works when the target is the first or last word in the original (hence the regex syntax
\bwhich means “word boundary”)Also, rename your method to
deleteAfterFirstOccurrence(), because your current name is misleading: The “last occurrence” is irrelevant to what you want.Here’s a little test:
Output: