So i'm trying to count the characters in a String without the spaces. But somehow my trim() method doesn't cut the spaces:
class Test {
HashMap<Character, Integer> testMap = new HashMap<>();
public void encode(String text) {
String code = text.trim();
for (int i = 0; i < code.length(); i++) {
Character key = code.charAt(i);
if (testMap.containsKey(key)) {
testMap.put(key, testMap.get(key) + 1);
} else {
testMap.put(key, 1);
}
}
System.out.println(testMap);
System.out.println(code);
}
Main method:
public class MyMain {
public static void main(String[] args) {
Test test = new Test();
test.encode("Tessstttt faill");
}
}
So the output is:
{ =1, a=1, s=3, T=1, t=4, e=1, f=1, i=1, l=2}
Tessstttt faill
Where is my mistake. Thanks a lot ahead!! (I'm not that experienced yet, so sorry in case of obvious mistake)
Return Value of trim() in Java The trim() method in Java returns a new string which is the copy of the original string with leading and trailing spaces removed from it.
The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
Trim won't remove all whitespace, only the leading and trailing. To remove all whitespace, you want something like this:
text.replaceAll("\\s","")
You misunderstood trim() it
Returns a copy of the string, with leading and trailing whitespace omitted.
Use replace()
instead to remove all the spaces
text.replace(" ","");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With