In the code below, I am trying to find each occurrence of 'C' in the string "CACA", remove it, then add the newly generated string to an array list. However, each occurrence should be removed once from the original string, which is "CACA" and once from each new string generated.
So the output should be as follows: [CACA, ACA, CAA, AA]
My code returns: [CACA, ACA, AA], so what am I missing?
ArrayList<String> array = new ArrayList<String>();
array.add("CACA");
String s = "C";
//ArrayList<String> newArray = new ArrayList<String>(); // create a new array to hold the new elements
for(int i = 0; i < array.size(); i++) {
for(int j = 0; j < array.get(i).length(); j++) {
if(s.equals(String.valueOf(array.get(i).charAt(j)))) {
if(array.get(i).length() == 1) {
array.add("e");
} else {
String a = String.valueOf(array.get(i).charAt(j));
int index = array.get(i).indexOf(a);
if(index == 0) {
String newStr = array.get(i).substring(1);
array.add(newStr);
} else if(index == array.get(i).length() - 1) {
String newStr = array.get(i).substring(0, array.get(i).length() - 1);
array.add(newStr);
} else {
String newStr = array.get(i).substring(0, index) + array.get(i).substring(index + 1);
array.add(newStr);
}
}
}
}
}
//System.out.println(newArray);
// add the new elements to the original array after the loop has finished
//array.addAll(newArray);
HashSet<String> setWithoutDuplicates = new HashSet<String>(array);
array.clear();
array.addAll(setWithoutDuplicates);
System.out.print(array);
Here is the problem with your code;
You start with an array list containing the string "CACA". Then you remove the first "C" and add the new string "ACA" to the array list twice.
int index = array.get(i).indexOf(a);
This code returns index 0 two times and causes duplicate strings in your array list.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string.
Your code never finds the index of second "C" in the string. So "CAA" doesn't get added to the array list. And the above code is unnecessary because you can already find the index of the char stored at the variable "j".
The for loop runs on the newly added strings "ACA" (both of them) and the "C" in the middle gets deleted. "AA" is added to the list twice. The process ends.
This is the solution:
ArrayList<String> array = new ArrayList<String>();
array.add("CACA");
String charToSearch = "C";
for(int i = 0; i < array.size(); i++) {
for(int j = 0; j < array.get(i).length(); j++) {
String currentCharAsString = String.valueOf(array.get(i).charAt(j));
if(charToSearch.equals(currentCharAsString)) {
if(array.get(i).length() == 1) {
array.add("e");
} else {
String newString = array.get(i).substring(0, j) + array.get(i).substring(j + 1);
//Check if the string is already added to the array list to prevent duplicates
if(!array.contains(newString))
array.add(newString);
}
}
}
}
System.out.print(array);