BACKGROUND for the QUESTION:
I am a beginner in JAVA. Application I am creating is a text Editor.
I am unable to create a loop to traverse through the entire text and
replace the occurrence of a string with another replacement string.
Any help would be appreciated..
regards,
Benny.
CODE:
public void replaceText(String search, String replacement, boolean
toreplaceAll) {
if (toreplaceAll == false) {
textComp.replaceSelection(replacement) ;
}
else {
String mainString = txtArea.getText() ;
int mainStringLength = mainString.length() ;
int index = mainString.indexOf(search,0) ;
StringBuffer sb = new StringBuffer(mainString) ;
sb.replace(index,(index + search.length()),replacement) ;
boolean anymorePatterns = true ;
int tempIndex = index ;
while( index <= mainStringLength && anymorePatterns == true) {
System.out.println("hello") ;
tempIndex = index ;
/* Problem lies here.. index does not move forward..
not able to find the next index.. why? */
index = mainString.indexOf(search,tempIndex) ;
/* ------------------------------------------ */
sb.replace
(index,index+search.length)),replacement) ;
if (tempIndex == index) {
anymorePatterns = false ;
System.out.println("tempindex is equal") ;
}
}
txtArea.setText(sb.toString()) ;
}
}