Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trim.() method does not work(java)

Tags:

java

string

trim

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)

like image 555
Noli Avatar asked May 14 '15 17:05

Noli


People also ask

Does trim () return in Java?

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.

What trim () method does in Java?

The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.

How do you remove leading and trailing spaces from a string in Java?

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.


2 Answers

Trim won't remove all whitespace, only the leading and trailing. To remove all whitespace, you want something like this:

text.replaceAll("\\s","")
like image 159
Eric Hotinger Avatar answered Oct 13 '22 22:10

Eric Hotinger


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(" ","");
like image 27
singhakash Avatar answered Oct 13 '22 23:10

singhakash