Whitespace Manipulation
Whitespace Manipulation Techniques
graph TD
A[Whitespace Manipulation] --> B[Removing]
A --> C[Replacing]
A --> D[Trimming]
A --> E[Normalizing]
Common Manipulation Methods
1. Removing Whitespace
public class WhitespaceRemoval {
public static void main(String[] args) {
String text = " Hello World \t\n";
// Remove all whitespace
String noWhitespace = text.replaceAll("\\s", "");
// Remove leading and trailing whitespace
String trimmed = text.trim();
System.out.println("Original: '" + text + "'");
System.out.println("No Whitespace: '" + noWhitespace + "'");
System.out.println("Trimmed: '" + trimmed + "'");
}
}
2. Replacing Whitespace
Method |
Description |
Example |
replaceAll() |
Replace all whitespace |
text.replaceAll("\\s", "-") |
replaceFirst() |
Replace first whitespace |
text.replaceFirst("\\s", "_") |
3. Whitespace Normalization
public class WhitespaceNormalization {
public static void main(String[] args) {
String text = "Hello World\t\nJava Programming";
// Normalize multiple whitespaces to single space
String normalized = text.replaceAll("\\s+", " ");
System.out.println("Original: '" + text + "'");
System.out.println("Normalized: '" + normalized + "'");
}
}
Advanced Manipulation Techniques
Regular Expression Strategies
graph LR
A[Regex Whitespace Manipulation] --> B[\\s Matches all whitespace]
A --> C[\\t Matches tabs]
A --> D[\\n Matches newlines]
A --> E[\\r Matches carriage returns]
Custom Whitespace Handling
public class CustomWhitespaceHandler {
public static String removeExtraWhitespace(String input) {
// Trim and replace multiple spaces with single space
return input.trim().replaceAll("\\s{2,}", " ");
}
public static void main(String[] args) {
String text = " Multiple Spaces Everywhere ";
System.out.println(removeExtraWhitespace(text));
}
}
- Use
trim()
for simple edge trimming
- Prefer
replaceAll()
for complex replacements
- Be cautious with regex on large strings
At LabEx, we emphasize efficient and clean text processing techniques that balance readability and performance.
Practical Use Cases
- Data cleaning
- User input validation
- Text formatting
- Log file processing
Best Practices
- Always validate input before manipulation
- Choose the most appropriate method for your specific scenario
- Consider performance implications of regex operations