How Can We Optimize a For Loop to Find Characters Around a Word in a String?

  • Thread starter Thread starter Arnoldjavs3
  • Start date Start date
  • Tags Tags
    Loop
AI Thread Summary
The discussion focuses on optimizing a Java method to extract characters surrounding a specified word in a string. The initial implementation successfully captures characters before and after the word but fails to account for cases where the word appears at the end of the string. A suggested improvement involves integrating the check for the last occurrence of the word within the loop to streamline the logic. Additionally, it's recommended to store the lengths of the string and word in local variables to enhance efficiency, avoiding repeated calls to length() during each iteration. Overall, the goal is to refine the code for better performance and accuracy.
Arnoldjavs3
Messages
191
Reaction score
3

Homework Statement


Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

Homework Equations

The Attempt at a Solution


Java:
public String wordEnds(String str, String word) {
  String newString = "";
 
  for(int i=0; i<str.length()-word.length(); i++) {
    int finalCheck = str.length()-word.length();
    if(str.substring(i, i+word.length()).equals(word)) {
      if(i!=0) {
        newString += "" + str.charAt(i-1);
      }
      newString += "" + str.charAt(i+word.length());
     
    }
  }
  return newString;
}
This code works in all cases unless the word is at the last index(e.g: wordEnds("abc1xyz1abc", "abc") → "11" got "1"
wordEnds("abc1abc1abc", "abc") → "1111" got "111") It isn't adding the last char before the last index.)
So I made this code which works but it's not incorporated for inside the loop which I'd like to do
Java:
public String wordEnds(String str, String word) {
  String newString = "";
 
  for(int i=0; i<str.length()-word.length(); i++) {
    int finalCheck = str.length()-word.length();
    if(str.substring(i, i+word.length()).equals(word)) {
      if(i!=0) {
        newString += "" + str.charAt(i-1);
      }
      newString += "" + str.charAt(i+word.length());
     
    }
  }
  int finalOccurence = str.length()-word.length();
  if(str.length()>word.length()&&str.substring(finalOccurence).equals(word)) {
    newString+="" + str.charAt(finalOccurence-1);
  }
 
  return newString;
}
 
Physics news on Phys.org
Arnoldjavs3 said:

Homework Statement


Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

Homework Equations

The Attempt at a Solution


Java:
public String wordEnds(String str, String word) {
  String newString = "";
 
  for(int i=0; i<str.length()-word.length(); i++) {
    int finalCheck = str.length()-word.length();
    if(str.substring(i, i+word.length()).equals(word)) {
      if(i!=0) {
        newString += "" + str.charAt(i-1);
      }
      newString += "" + str.charAt(i+word.length());
    
    }
  }
  return newString;
}
This code works in all cases unless the word is at the last index(e.g: wordEnds("abc1xyz1abc", "abc") → "11" got "1"
wordEnds("abc1abc1abc", "abc") → "1111" got "111") It isn't adding the last char before the last index.)
So I made this code which works but it's not incorporated for inside the loop which I'd like to do
Java:
public String wordEnds(String str, String word) {
  String newString = "";
 
  for(int i=0; i<str.length()-word.length(); i++) {
    int finalCheck = str.length()-word.length();
    if(str.substring(i, i+word.length()).equals(word)) {
      if(i!=0) {
        newString += "" + str.charAt(i-1);
      }
      newString += "" + str.charAt(i+word.length());
    
    }
  }
  int finalOccurence = str.length()-word.length();
  if(str.length()>word.length()&&str.substring(finalOccurence).equals(word)) {
    newString+="" + str.charAt(finalOccurence-1);
  }
 
  return newString;
}
Without looking that closely at your code, it seems to me that you could put the logic of checking for the last word as an if statement inside the for loop. I would structure it so that the if clause executes if the word isn't the last word, and the else clause handles the case when the word is the last word. In other words, the part right after if is set up to execute most often.

Also, as far as I can tell, since str and word are passed as parameters to your wordEnds() function, your code is using length() unnecessarily. I would calculate str.length() and word.length() once at the top of the function, and store these values in local variables. It's very inefficient to call a function multiple times in each loop iteration if the lengths aren't actually changing.
 

Similar threads

Replies
5
Views
3K
Replies
3
Views
2K
Replies
12
Views
2K
Replies
1
Views
1K
Replies
1
Views
1K
Replies
24
Views
3K
Back
Top