- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete all whitespaces from a String in Java
To delete all whitespaces from a string, use the replaceAll() method and replace every whitespace with empty.
Let’s say the following is our string.
String str = "This is it!";
Now, let us replace the whitespaces that will eventually delete them.
String res = str.replaceAll("\s+","");
Example
public class Demo { public static void main(String []args) { String str = "This is it!"; System.out.println("String: "+str); String res = str.replaceAll("\s+",""); System.out.println("String after deleting whitespace: "+res); } }
Output
String: This is it! String after deleting whitespace: Thisisit!
Advertisements