Negative Indentation: Removing Leading Spaces
What you'll learn: How to use the indent() method with negative values to remove leading whitespace from strings, effectively "dedenting" text.
The Core Idea
While indent() with positive values adds spaces to the beginning of each line, passing a negative integer removes up to that many leading spaces from each line. This is incredibly useful when you need to reduce or eliminate indentation from multi-line text blocks, such as when processing formatted code, quoted text, or configuration files.
Think of it like adjusting a thermostat: positive values "heat up" (add spaces), negative values "cool down" (remove spaces). The method won't go below zero—it simply removes as many spaces as it can, up to the absolute value you specify.
How It Works
When you call indent(-n):
- Each line loses up to
nleading spaces - If a line has fewer than
nspaces, only the available spaces are removed - Non-space leading characters are never touched
- The method still normalizes line endings (like the positive version)
Practical Example
String indented = " Hello\n World\n Java";
String dedented = indented.indent(-2);
// Result:
// " Hello\n World\n Java\n"
// Each line lost 2 spaces
String fullyDedented = indented.indent(-10);
// Result:
// "Hello\nWorld\nJava\n"
// All leading spaces removed (even though we asked for 10)
This is particularly handy for cleaning up text blocks that were over-indented or for "normalizing" code snippets by removing common leading whitespace.
Key Takeaway: The indent() method with negative values removes up to n leading spaces from each line, providing an elegant way to dedent multi-line strings without manually parsing each line.