Java > AP-1 > wordsWithout (CodingBat Solution)

Problem:

Given an array of strings, return a new array without the strings that are equal to the target string. One approach is to count the occurrences of the target string, make a new array of the correct length, and then copy over the correct strings.

wordsWithout({"a", "b", "c", "a"}, "a") → {"b", "c"}
wordsWithout({"a", "b", "c", "a"}, "b") → {"a", "c", "a"}
wordsWithout({"a", "b", "c", "a"}, "c") → {"a", "b", "a"}


Solution:

public String[] wordsWithout(String[] words, String target) {
  int found = 0;
  
  for (int i = 0; i < words.length; i++) {
    if (words[i].equals(target))
      found++;
  }
  found = words.length - found;
  int place = 0;
  
  String[] str = new String[found];
  for (int j = 0; j < words.length; j++) {
    if (!words[j].equals(target)) {
      str[place] = words[j];
      place++;
    }
  }
  return str;
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact