Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Beginner Question: String.indexOf

  Asked By: Annie    Date: Jun 20    Category: Java    Views: 1447
  

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()) ;

}

}

Share: 

 

No Answers Found. Be the First, To Post Answer.

 
Didn't find what you were looking for? Find more on Beginner Question: String.indexOf Or get search suggestion and latest updates.




Tagged: