I have the following code,
String s = " Hello I'm a multi spaced String"
In string s, there are multiple (indeterminate) spaces; but, I need to print it as %temp%Hello I'm a%temp%multi spaced String
How can I do this?
One way to do this is with string format codes. For example, if you want to pad a string to a certain length with spaces, use something like this: String padded = String. format("%-20s", str);
The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.
Use regex \s{2,}
and replaceAll()
method like this:
s.replaceAll("\\s{2,}","%temp%");
Output
%temp%Hello I'm a%temp%multi spaced String
Code
public class HelloWorld
{
public static void main(String[] args)
{
String s = " Hello I'm a multi spaced String";
s = s.replaceAll("\\s{2,}","%temp%");
System.out.println(s);
}
}
You can use a regular expression like \s\s+
which matches a white space followed by one or more additional whitespaces. Something like,
String s = " Hello I'm a multi spaced String";
s = s.replaceAll("\\s\\s+", "%temp%");
System.out.println(s);
Outputs (as requested)
%temp%Hello I'm a%temp%multi spaced String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With