To remove leading spaces (whitespace characters at the beginning of a string) in Java, you can use the trim
method of the String
class. The trim
method returns a new string with leading and trailing whitespace characters removed.
Here is an example of how you can use the trim
method to remove leading spaces from a string in Java:
String originalString = " Hello, World!"; String modifiedString = originalString.trim(); System.out.println(modifiedString); // Outputs "Hello, World!"
In this example, the trim
method is called on the originalString
string, which removes the leading spaces and returns a new modifiedString
string with the leading spaces removed.
You can also use the replaceAll
method or regular expressions to remove specific characters or patterns from a string. For example, to remove only leading spaces, you can use the following regular expression:
String modifiedString = originalString.replaceAll("^\\s+", "");
This regular expression will match one or more leading whitespace characters (\\s
) and replace them with an empty string (""
).
Keep in mind that the trim
and replaceAll
methods operate on the original string and return a new modified string, without changing the original string. If you want to modify the original string, you can assign the modified string back to the original string variable, or use a StringBuilder
object.