Strip Leading and Trailing Spaces from Java String

How to remove leading and trailing whitespace from the string in Java?

 s.trim()

see String#trim()

Without any internal method, use regex like

 s.replaceAll("^\\s+", "").replaceAll("\\s+$", "")

or

  s.replaceAll("^\\s+|\\s+$", "")

or just use pattern in pure form

    String s="          Hello World                    ";
Pattern trimmer = Pattern.compile("^\\s+|\\s+$");
Matcher m = trimmer.matcher(s);
StringBuffer out = new StringBuffer();
while(m.find())
m.appendReplacement(out, "");
m.appendTail(out);
System.out.println(out+"!");

Strip Leading and Trailing Spaces From Java String

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs

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

How to remove a white space at the end of a string in java?

If you just want to trim whitespace at the end, use String#replaceAll() with an appropriate regex:

String input = " XXXX ";
String output = input.replaceAll("\\s+$", "");
System.out.println("***" + input + "***"); // *** XXXX ***
System.out.println("***" + output + "***"); // *** XXXX***

If you really want to replace just one whitespace character at the end, then replace on \s$ instead of \s+$.

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.

removing trailing and leading spaces from a file

You do not need to worry about the length of the string passed to strstrip(), simply iterate over all characters in the string removing whitespace characters, e.g. the following version removals ALL whitespace from s:

/** remove ALL leading, interleaved and trailing whitespace, in place.
* the original start address is preserved but due to reindexing,
* the contents of the original are not preserved. returns pointer
* to 's'. (ctype.h required)
*/
char *strstrip (char *s)
{
if (!s) return NULL; /* valdiate string not NULL */
if (!*s) return s; /* handle empty string */

char *p = s, *wp = s; /* pointer and write-pointer */

while (*p) { /* loop over each character */
while (isspace ((unsigned char)*p)) /* if whitespace advance ptr */
p++;
*wp++ = *p; /* use non-ws char */
if (*p)
p++;
}
*wp = 0; /* nul-terminate */

return s;
}

(note: if the argument to isspace() is type char, a cast to unsigned char is required, see NOTES Section, e.g. man 3 isalpha)

Removing only Excess Whitespace

The following version removes leading and trailing whitespace and collapses multiple sequences of whitespace to a single space:

/** remove excess leading, interleaved and trailing whitespace, in place.
* the original start address is preserved but due to reindexing,
* the contents of the original are not preserved. returns pointer
* to 's'. (ctype.h required) NOTE: LATEST
*/
char *strstrip (char *s)
{
if (!s) return NULL; /* valdiate string not NULL */
if (!*s) return s; /* handle empty string */

char *p = s, *wp = s; /* pointer and write-pointer */

while (*p) {
if (isspace((unsigned char)*p)) { /* test for ws */
if (wp > s) /* ignore leading ws, while */
*wp++ = *p; /* preserving 1 between words */
while (*p && isspace (unsigned char)(*p)) /* skip remainder */
p++;
if (!*p) /* bail on end-of-string */
break;
}
if (*p == '.') /* handle space between word and '.' */
while (wp > s && isspace ((unsigned char)*(wp - 1)))
wp--;
*wp++ = *p; /* use non-ws char */
p++;
}
while (wp > s && isspace ((unsigned char)*(wp - 1))) /* trim trailing ws */
wp--;
*wp = 0; /* nul-terminate */

return s;
}

(note: s must be mutable and therefore cannot be a string-literal)



Related Topics



Leave a reply



Submit