How to remove only trailing spaces of a string in Java and keep leading spaces?
Since JDK 11
If you are on JDK 11 or higher you should probably be using stripTrailing().
Earlier JDK versions
Using the regular expression \s++$
, you can replace all trailing space characters (includes space and tab characters) with the empty string (""
).
final String text = " foo ";
System.out.println(text.replaceFirst("\\s++$", ""));
Output
foo
Online demo.
Here's a breakdown of the regex:
\s
– any whitespace character,++
– match one or more of the previous token (possessively); i.e., match one or more whitespace character. The+
pattern is used in its possessive form++
, which takes less time to detect the case when the pattern does not match.$
– the end of the string.
Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.
The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.
References
- Java regular expression syntax
Remove Whitespaces ONLY at the end of a String (java)
If your goal is to cut only the trailing white space characters and to save leading white space characters of your String, you can use String
class' replaceFirst()
method:
String yourString = " my text. ";
String cutTrailingWhiteSpaceCharacters = yourString.replaceFirst("\\s++$", "");
\\s++
- one or more white space characters (use of possesive quantifiers (take a look at Pattern
class in the Java API documentation, you have listed all of the special characters used in regułar expressions there)),
$
- end of string
You might also want to take a look at part of my answer before the edit:
If you don't care about the leading white space characters of your input String:String
class provides a trim()
method. It might be quick solution in your case as it cuts leading and trailing whitespaces of the given String.
Remove every space EXCEPT leading spaces
You can use replaceAll with this regex (?<=\S)(\s+)(?=\S)
like this :
str = str.replaceAll("(?<=\\S)(\\s+)(?=\\S)", "");
Examples of input & outputs:
" h ello " => " hello "
" hello, word " => " hello,word "
The first regex keep only leading and trailing spaces, if you want to keep only the leading spaces, then you can use this regex (?<=\S)(\s+)
.
Examples of input & outputs:
" hello " => " hello"
" hello, word " => " hello,word"
Strip Leading and Trailing Spaces From Java String
You can try the trim() method.
String newString = oldString.trim();
Take a look at javadocs
Remove first white space in Java
Just use str.trim()
to get rid of all leading and trailing spaces.
Removing contiguous spaces in a String without trim() and replaceAll()
I'm not permitted to use these methods. I've to do this with loops
and all.
So i wrote for you some little snipet of code if you can't use faster and more efficient way:
String str = " this is a string containing numerous whitespaces ";
StringBuffer buff = new StringBuffer();
String correctedString = "";
boolean space = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
if (!space && i > 0) {
buff.append(c);
}
space = true;
}
else {
buff.append(c);
space = false;
}
}
String temp = buff.toString();
if (temp.charAt(temp.length() - 1) == ' ') {
correctedString = temp.substring(0, buff.toString().length() - 1);
System.out.println(correctedString);
}
System.out.println(buff.toString())
Note:
But this is "harcoded" and only for "learning".
More efficient way is for sure use approaches pointed out by @JonSkeet and @BrunoReis
How to remove spaces from string only if it occurs once between two words but not if it occurs thrice?
You could use lookarounds to do your replacement:
String newText = text
.replaceAll("(?<! ) (?! )", "")
.replaceAll(" +", " ");
The first replaceAll
removes any space not surrounded by spaces; the second one replaces the remaining sequences of spaces by a single one.
Ideone example. Sequences of two or more spaces become a single space, and single spaces are removed.
Lookarounds
A lookaround in the context of regular expressions is a collective term for lookbehinds and lookaheads. These are so-called zero-width assertions, that means they match a certain pattern, but do not actually consume characters. There are positive and negative lookarounds.
A short example: the pattern Ira(?!q)
matches the substring Ira
, but only if it's not followed by a q
. So if the input string is Iraq
, it won't match, but if the input string is Iran
, then the match is Ira
.
More info:
- https://www.regular-expressions.info/lookaround.html
Swift remove ONLY trailing spaces from string
A quite simple solution is regular expression, the pattern is one or more(+
) whitespace characters(\s
) at the end of the string($
)
let string = " keep my left side "
let cleansed = string.replacingOccurrences(of: "\\s+$",
with: "",
options: .regularExpression)
Related Topics
String-Date Conversion with Nanoseconds
Connectiontimeout Versus Sockettimeout
Android Intent for Sending Email with Attachment
Tm.Getdeviceid() Is Deprecated
How to Print to the Console in Android Studio
Android Color Between Two Colors, Based on Percentage
Android Call a Method from Another Class
How to Read Data from Xls (Excel) File [Java, Android]
Hbase Client Connectionloss for /Hbase Error
Polygon Touch Detection Google Map API V2
Android Buildscript Repositories: Jcenter VS Mavencentral
How to Move/Rename File from Internal App Storage to External Storage on Android
Noclassdeffounderror on External Library Project for Android
What Is the Equivalent to a JavaScript Setinterval/Settimeout in Android/Java
Android: Why Setvisibility(View.Gone); or Setvisibility(View.Invisible); Do Not Work