Reputation: 1240
I have a string like
'John is a student. He is also a researcher. He is also a human.'
I have start and end indexes of John
and first He
. Is there a way to replace these substrings simultaneously with x
. Note that I should not replace second He
because I have indexes only for the first He
.
We can obviously iterate over string, copy whenever the pointer is not in the window of substring and putting x
instead. But, is there a better way than this?
Also, note that indexes are non-overlapping.
Upvotes: 0
Views: 1498
Reputation: 1240
Replacing from the end is the best solution.
public class NE {
public Integer startIndex;
public Integer endIndex;
}
public class CustomComparator implements Comparator<NE> {
public int compare(NE n1, NE n2) {
return n1.startIndex.compareTo(n2.startIndex);
}
}
ArrayList<NE> NEList = getIndexes();
Collections.sort(NEList, ner.new CustomComparator());
String finalString = 'John is a student. He is also a researcher. He is also a human.';
for(int i=NEList.size()-1;i>=0;i--){
NE ne = ner.new NE();
ne = NEList.get(i);
finalString = new StringBuilder(finalString).replace(ne.startIndex, ne.endIndex, 'x').toString();
}
System.out.println(finalString);
Credits: @AndyTurner
Upvotes: 3
Reputation: 1144
You can use a placeholder with the same lenght of the word to replace.Then replace the placeholders with x and get the result.
String s = "John is a student. He is also a researcher.";
int firstStart = 0,firstEnd =4,secondStart=19,secondEnd=21;
String firstPlaceholder = String.format("%"+(firstEnd - firstStart )+"s", " ").replaceAll(" ", "x");
String secondPlaceholder = String.format("%"+(secondEnd -secondStart)+"s", " ").replaceAll(" ", "x");
String result = new StringBuilder(s).replace(firstStart, firstEnd, firstPlaceholder)
.replace(secondStart, secondEnd, secondPlaceholder)
.toString().replaceAll("x[x]+", "x");
System.out.println( result);
output:
x is a student. x is also a researcher.
hope this can help.
Upvotes: 0
Reputation: 119
try this :
String s="John is a student. He is also a researcher.";
int beginIndex=s.indexOf("He");
s=s.substring(0, beginIndex)+"x"+s.substring(beginIndex+2,s.length());
Output : John is a student. x is also a researcher.
Upvotes: 0
Reputation: 1227
I do not know about a way to change both with the index. But hey, you probably first found the index by searching for the substrings John and He. So you could skip that and use the Strings static method replaceAll
.
String test = "John is a student. He is also a researcher.";
System.out.println(test.replaceAll("(John)|(He)", "x"));
In fact you are checking if (John)|(He)
("John" or "He") are in the string test. If so they are replaced by "x"
.
replaceAll
returns a reference to a new String object looking like:
x is a student. x is also a researcher.
Upvotes: 0