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
Click For Summary
SUMMARY

The forum discussion focuses on optimizing a Java method, wordEnds, designed to extract characters surrounding a specified word in a string. The initial implementation fails to account for cases where the word appears at the end of the string, leading to incomplete results. A revised version successfully addresses this issue by adding a check for the last occurrence of the word outside the loop. Additionally, suggestions include reducing the number of calls to length() by storing the lengths of the string and word in local variables for improved efficiency.

PREREQUISITES
  • Java programming language fundamentals
  • Understanding of string manipulation in Java
  • Knowledge of control structures, specifically loops and conditionals
  • Basic performance optimization techniques in coding
NEXT STEPS
  • Explore Java String methods, particularly substring() and charAt()
  • Learn about performance optimization in Java, focusing on reducing method calls
  • Investigate advanced string handling techniques, such as using StringBuilder for concatenation
  • Study the implementation of unit tests in Java to validate string manipulation functions
USEFUL FOR

Java developers, software engineers, and computer science students interested in string manipulation and performance optimization techniques.

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 ·
Replies
5
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
10K
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K