Reputation: 231
I'm pretty new to Java and I have a problem and I can't seem to find the answer to it. I'm trying to find out if the language I pass exists in my list.
String lang = "fr, de, gb, nl, se, es";
List<String> result = new ArrayList<String>();
String[] languages = lang.split(",");
result = Arrays.asList(languages);
if (result.contains("de")) {
return true;
} else {
System.exit(0);
}
And this returns false, i can't understand why.
Upvotes: 0
Views: 96
Reputation: 71
That's because array languages" contains {"fr"," de"," gb"," nl"," se"," es"} it contains " de" not "de". You can correct it in two different ways, 1: Split languages with " ," (syntax may be different). 2: compare the correct strings including space.
Upvotes: 2
Reputation: 200138
You are splitting on just the comma, therefore your array contains strings with spaces in front. Use this regex instead to split:
lang.split("\\s*,\\s*")
On a side note, you don't need these three lines:
List<String> result = new ArrayList<String>();
String[] languages = lang.split(...);
result = Arrays.asList(languages);
All you need is
List<String> result = Arrays.asList(lang.split(...));
Upvotes: 4
Reputation: 622
change your string like this
String lang = "fr,de,gb,nl,se,es";
or change like @TheLostMoind said
Upvotes: -2
Reputation: 201399
You get the spaces with your split, I would use split with \\s+
which will remove the white space for you.
String lang = "fr, de, gb, nl, se, es";
String[] languages = lang.split(",\\s+");
List<String> result = Arrays.asList(languages);
if (result.contains("de")) {
System.out.println("Result contains de");
} else {
System.out.println("Result does not contain de");
}
Output is
Result contains de
Upvotes: 1
Reputation: 947
Split the lang String after ", " or remove the spaces in the initialization
Upvotes: 0
Reputation: 5123
Your strings are separated with ", ". so if you do this:
if (result.contains(" de")
it will work.
Upvotes: 0
Reputation: 36304
"fr, de, gb, nl, se, es"
you are checking for de
instead of <space>de
.
Upvotes: 0