[Java] Remove whitespace from character strings

trim() If you want to remove the whitespace before and after the string, use the ** trim ** method. However, white space in the middle of the character string is not subject to removal.

trim.java


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String str = "   Hello, World   ";
        //Remove whitespace before and after the string
        System.out.println(str.trim());
    }
}

result


Hello, World

replaceAll() If you want to remove all whitespace in the string, use the ** replaceAll ** method.

trim.java


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String str = "   Hello, World   ";
        //Remove all whitespace
        System.out.println(str.replaceAll(" ",""));
    }
}

result


Hello,World

Recommended Posts

[Java] Remove whitespace from character strings
Java (remove)
OCR in Java (character recognition from images)
Remove ASCII code control characters from strings
[Java] Precautions when comparing character strings with character strings
[Java] Comparison of String type character strings
Manipulating Java strings
Java character code
[java] Summary of how to handle character strings
Call Java from JRuby
Changes from Java 8 to Java 11
Sum from Java_1 to 100
[Java] Convert character strings to uppercase / lowercase (AOJ⑨-swap uppercase and lowercase)
Eval Java source from Java
Access API.AI from Java
From Java to Ruby !!
[Java] How to erase a specific character from a character string
Reverse Enum constants from strings and values in Java
About full-width ⇔ half-width conversion of character strings in Java
[Java] Handling of character strings (String class and StringBuilder class)
[Java] Comparison method of character strings and comparison method using regular expressions
[Java] How to convert a character string from String type to byte type
Correct the character code in Java and read from the URL
[Introduction to Java] Handling of character strings (String class, StringBuilder class)
Migration from Cobol to JAVA
Basics of character operation (java)
Java starting from beginner, override
Creating ElasticSearch index from Java
Sort strings functionally with java
Connect from Java to PostgreSQL
Java, instance starting from beginner
[Ruby] Repeating arbitrary character strings
Java starting from beginner, inheritance
Java life starting from scratch
Using Docker from Java Gradle
Display character strings character by character [Note]
From Ineffective Java to Effective Java
JavaScript as seen from Java
Execute non-Java instructions from Java