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

  • Thread starter Arnoldjavs3
  • Start date
  • Tags
    Loop
In summary, the code for the function wordEnds() takes in a string and a word, and returns a new string made up of the characters before and after each appearance of the word in the string. It ignores cases where there is no character before or after the word, and a character may be included twice if it is between two words. The code checks for the last word in the string and adds the appropriate character before it, and also calculates the length of the string and word only once for efficiency.
  • #1
Arnoldjavs3
191
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
  • #2
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.
 

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

1. How can I make my for loop more efficient?

One way to make a for loop more efficient is by minimizing the number of iterations. This can be achieved by using a more appropriate loop structure or by using a conditional statement within the loop to skip unnecessary iterations.

2. Is it better to use a while loop or a for loop for efficiency?

It depends on the specific task at hand. While loops are generally better for tasks that require a variable number of iterations, while for loops are better for tasks with a fixed number of iterations. In terms of efficiency, the difference between the two is negligible.

3. How can I optimize my for loop for performance?

Some ways to optimize a for loop for performance include minimizing the number of function calls within the loop, using efficient data structures, and avoiding unnecessary operations such as concatenating strings.

4. Can I use parallelism to make my for loop more efficient?

Yes, parallelism can be used to improve the efficiency of a for loop. By dividing the loop into smaller tasks that can be executed simultaneously on different processors, the overall execution time can be reduced.

5. Are there any tools or techniques that can help me analyze the efficiency of my for loop?

Yes, there are various tools and techniques available for analyzing the efficiency of a for loop. Some popular ones include profiling tools, which measure the execution time of different parts of the code, and algorithm analysis, which can help identify areas for improvement in the loop structure.

Similar threads

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