For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
In Java programming, manipulating strings efficiently is a crucial skill. One common task is removing whitespace from strings, eliminating unnecessary space to optimize text processing.
In this article, we will explore various techniques to remove whitespace from string in java, while also discussing alternative approaches in other programming languages such as Java Script, Python, C++, and C#. We will cover the built-in methods in Java, such as trim(), strip(), stripLeading(), stripTrailing(), and replaceAll(), along with custom implementations.
So, let's dive into the world of whitespace removal in Java!
Whitespace refers to any non-visible characters within a string, including spaces, tabs, and line breaks. Removing these whitespace characters can significantly improve the efficiency of string operations and enhance memory usage.
In the following sections, we will explore different methods to achieve this optimization in Java, focusing on simplicity and effectiveness.
In Java, there are multiple approaches to remove whitespace from a string. Let's explore each method in detail:
The trim() method is a built-in function in Java that removes leading and trailing whitespace from a string. It trims spaces from both ends of the string, leaving the internal whitespace intact. For example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // Output: "Hello, World!"
}
}
Output:
Hello, World!
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.
To remove the leading and trailing whitespace from the string, we use the trim() method. The trim() method is a built-in function in Java's String class that eliminates leading and trailing whitespace characters.
We then assign the trimmed string to the variable trimmedStr. Finally, we print the value of trimmedStr to the console using System.out.println(), which will output "Hello, World!".
When you run this Java program, you will see the output "Hello, World!", demonstrating the removal of whitespace from the original string.
Introduced in Java 11, the strip() method removes leading and trailing whitespace from a string, similar to trim(). However, strip() is more powerful as it can handle Unicode whitespace characters as well. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String strippedStr = str.strip();
System.out.println(strippedStr); // Output: "Hello, World!"
}
}
Output:
Hello, World!
This is because the strip() method removes the leading and trailing whitespace from the string " Hello, World! ", resulting in the trimmed string "Hello, World!". The System.out.println() statement prints this trimmed string to the console, displaying "Hello, World!" as the output.
The stripLeading() method, introduced in Java 11, removes only the leading whitespace from a string, leaving trailing whitespace intact. It also handles Unicode whitespace characters. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String strippedStr = str.stripLeading();
System.out.println(strippedStr); // Output: "Hello, World! "
}
}
Output:
Hello, World!
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.
To remove only the leading whitespace from the string, we use the stripLeading() method. The stripLeading() method is a built-in function introduced in Java 11 that trims the whitespace from the beginning of the string while leaving the trailing whitespace intact.
We then assign the stripped string to the variable strippedStr. Finally, we print the value of strippedStr to the console using System.out.println(), which will output "Hello, World! ".
The stripTrailing() method, introduced in Java 11, removes only the trailing whitespace from a string, leaving the leading whitespace intact. It handles Unicode whitespace characters as well. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String strippedStr = str.stripTrailing();
System.out.println(strippedStr); // Output: " Hello, World!"
}
}
Output:
Hello, World!
In the given code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, World! ". This string contains leading and trailing whitespace.
To remove only the trailing whitespace from the string, we use the stripTrailing() method. The stripTrailing() method is a built-in function introduced in Java 11 that trims the whitespace from the end of the string while leaving the leading whitespace intact.
We then assign the stripped string to the variable strippedStr. Finally, we print the value of strippedStr to the console using System.out.println(), which will output " Hello, World!".
The replaceAll() method with regular expressions lets you remove all whitespace characters from a string, including spaces, tabs, and line breaks. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, \nWorld! ";
String noWhitespaceStr = str.replaceAll("\\s", "");
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
}
Output:
In the given code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces and a newline character.
To remove all whitespace characters from the string, we use the replaceAll() method along with the regular expression pattern "\\s". The "\\s" pattern matches any whitespace character, including spaces, tabs, and newline characters. We replace all occurrences of whitespace with an empty string "".
We then assign the resulting string to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".
Now let's explore two additional methods to remove all whitespace characters from a string in Java:
By combining multiple string class functions, we can remove all whitespace characters from a string. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, \nWorld! ";
String noWhitespaceStr = str.replace(" ", "").replace("\t", "").replace("\n", "");
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
}
Output:
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces, tabs, and a newline character.
We use the replace() method multiple times to remove all whitespace characters from the string. We chain the replace() method calls to individually remove spaces, tabs, and newline characters. In each replace() call, we specify the whitespace character to be replaced with an empty string "".
We then assign the resulting string to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".
The Character class in Java provides handy functions to determine if a character is whitespace. By iterating through the characters of a string, we can filter out the whitespace characters. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, \nWorld! ";
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
String noWhitespaceStr = sb.toString();
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
}
Output:
In the above code, we have a Java class named WhitespaceRemoval. Inside the main method, we declare a string variable str and assign it the value " Hello, \nWorld! ". This string contains various whitespace characters, including spaces, tabs, and a newline character.
To remove all whitespace characters from the string, we use a StringBuilder to build the resulting string without whitespace. We iterate through each character of the input string using a for loop and check if the character is not a whitespace character using the Character.isWhitespace() method. We append it to the StringBuilder if it's not a whitespace character.
After iterating through all the characters, we convert the StringBuilder to a string using the toString() method and assign it to the variable noWhitespaceStr. Finally, we print the value of noWhitespaceStr to the console using System.out.println(), which will output "Hello,World!".
You can use a combination of string manipulation techniques to remove whitespace from a string in Java without using the replace() method. Here's an example approach:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String noWhitespaceStr = removeWhitespace(str);
System.out.println(noWhitespaceStr); // Output: "Hello,World!"
}
public static String removeWhitespace(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : chars) {
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
}
Output:
Hello, World!
To remove whitespace from a string in Java without using the replace() method, you can iterate through each character of the string and append non-whitespace characters to a StringBuilder. Finally, convert the StringBuilder to a string. This approach avoids direct replacement and produces a new string without whitespace.
To remove whitespace from the beginning and end of a string in Java, you can use the Java trim. The trim() method is a built-in function that eliminates leading and trailing whitespace characters. Here's an example:
public class WhitespaceRemoval {
public static void main(String[] args) {
String str = " Hello, World! ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // Output: "Hello, World!"
}
}
In the above code, the string " Hello, World! " contains whitespace characters at the beginning and end.
By applying the trim() method to the string, we remove those leading and trailing whitespace characters. The resulting string, "Hello, World!", is then printed to the console.
Removing whitespace from strings is a common requirement in Java programming. In this article, we explored various methods to achieve efficient string manipulation by removing whitespace. We covered built-in functions like trim(), strip(), stripLeading(), stripTrailing(), and replaceAll(), along with custom implementations using string class functions and the Character class. By utilizing these techniques, you can optimize your code for improved performance and memory usage. So, the next time you encounter whitespace removal in Java, choose the appropriate method based on your specific needs and achieve efficient string manipulation.
1. How does the trim() method in Java remove whitespace from a string?
The trim() method removes leading and trailing whitespace characters from a string, including spaces, tabs, and newline characters. It returns a new string with the whitespace removed.
2. How can I remove only the leading whitespace from a string in Java?
To remove only the leading whitespace from a string, use the stripLeading() method introduced in Java 11. It trims the whitespace from the beginning of the string while leaving the trailing whitespace intact.
3. How can I remove only trailing whitespace from a string in Java?
To remove only trailing whitespace from a string, use the stripTrailing() method introduced in Java 11. It trims the whitespace from the end of the string while preserving the leading whitespace.
4. How does the trim() method differ from the replaceAll() method for removing whitespace in Java?
The trim() method removes leading and trailing whitespace characters, while the replaceAll() method replaces all occurrences of a specified pattern with a replacement string. The trim() method is specifically designed for removing whitespace from the beginning and end of a string, while replaceAll() provides more flexibility for replacing specific patterns throughout the string.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.