I need some help to fix my issue as I described below:
I have an array list with name datalist and it has elements like ah3w 38 45 1, zj4e 32 4 45. I want to compare a string like ah3w 38 45 1 for checking is it in arraylist or not. The main problem is whitespaces. I want to ignore them because sometimes I have elements in arraylist which has more than one white space between characters. I had tried something like below with using replaceAll method, but it didnt work. Lastly I tried to remove all white space before I created the arraylist, then I did same thing for my string too, it worked but it is not like I want. I dont want to change anything I just want to compare them without spaces. Here is my code example:
String field = "ah3w 38 45 1"
for(int a=0; a<datalist.size(); a++){
if(datalist.get(a).replaceAll("\\s+","").contains(field.replaceAll("\\s+",""))){
datalist.remove(a);
}
}
Here is another code block that is doing same thing and you can run and see what I am trying to do and what ı am getting:
import java.util.ArrayList;
public class ReplaceAllElementsOfArrayListExample {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
String field= "ah3w 38 45 1";
arrayList.add("zj4e 32 4 45");
arrayList.add("ah3w 38 45 1");
arrayList.add("ab2 56 2 45");
System.out.println("Before replacement, ArrayList contains : " + arrayList);
if(arrayList.get(1).replaceAll("\\s+","").contains(field.replaceAll("\\s+",""))){
System.out.println("They are equal : " + arrayList);}
else{
System.out.println("They are not equal : " + arrayList);
}
}
}
Try this:
ArrayList<String> arrayList = new ArrayList<String>();
String field = "ah3w 38 45 1";
arrayList.add("zj4e 32 4 45");
arrayList.add("ah3w 38 45 1");
arrayList.add("ab2 56 2 45");
//solution
String fieldNoWhitespaces = field.replaceAll("\\s", "");
for (String dataElement : arrayList) {
String arg = dataElement.replaceAll("\\s", "");
if (fieldNoWhitespaces.equals(arg)) arrayList.remove(dataElement);
}
//just to check for correctness
for (String dataElement : arrayList) {
System.out.println(":::" + dataElement);
int count = 0;
for (int i = 0; i < dataElement.length(); i++) {
if (Character.isWhitespace(dataElement.charAt(i))) {
count++;
}
}
System.out.println(":::Whitespaces:::" + count);
}
Output:
:::zj4e 32 4 45
:::Whitespaces:::6
:::ab2 56 2 45
:::Whitespaces:::3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.