web-dev-qa-db-fra.com

Supprimer les espaces de début et de fin de la chaîne Java

Existe-t-il une méthode pratique permettant de supprimer les espaces de début ou de fin d'une chaîne Java?

Quelque chose comme:

String myString = "  keep this  ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);

Résultat:

no spaces:keep this

myString.replace(" ","") remplacerait l'espace entre keep et this.

Merci

247
Tyler DeWitt

Vous pouvez essayer la méthode trim ().

String newString = oldString.trim();

Jetez un oeil à javadocs

558
woliveirajr

Utilisez String#trim() method ou String allRemoved = myString.replaceAll("^\\s+|\\s+$", "") pour couper les deux extrémités.

Pour la garniture gauche:

String leftRemoved = myString.replaceAll("^\\s+", "");

Pour une bonne coupe:

String rightRemoved = myString.replaceAll("\\s+$", "");
76
Prince John Wesley

De la docs :

String.trim();
29
Richard H

trim () est votre choix, mais si vous souhaitez utiliser la méthode replace - qui pourrait être plus flexible, vous pouvez essayer les solutions suivantes:

String stripppedString = myString.replaceAll("(^ )|( $)", "");
14
James.Xu

Avec Java-11 maintenant, vous pouvez utiliser l’API String.strip pour renvoyer une chaîne dont la valeur est cette chaîne, tous les espaces en début et en fin étant supprimés. Le javadoc pour le même lit comme suit:

/**
 * Returns a string whose value is this string, with all leading
 * and trailing {@link Character#isWhitespace(int) white space}
 * removed.
 * <p>
 * If this {@code String} object represents an empty string,
 * or if all code points in this string are
 * {@link Character#isWhitespace(int) white space}, then an empty string
 * is returned.
 * <p>
 * Otherwise, returns a substring of this string beginning with the first
 * code point that is not a {@link Character#isWhitespace(int) white space}
 * up to and including the last code point that is not a
 * {@link Character#isWhitespace(int) white space}.
 * <p>
 * This method may be used to strip
 * {@link Character#isWhitespace(int) white space} from
 * the beginning and end of a string.
 *
 * @return  a string whose value is this string, with all leading
 *          and trailing white space removed
 *
 * @see Character#isWhitespace(int)
 *
 * @since 11
 */
public String strip()

Les exemples de cas pour ceux-ci pourraient être: -

System.out.println("  leading".strip()); // prints "leading"
System.out.println("trailing  ".strip()); // prints "trailing"
System.out.println("  keep this  ".strip()); // prints "keep this"
2
nullpointer

Pour couper un caractère spécifique, vous pouvez utiliser:

String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")

Ici, les bandes space et virgule sont supprimées.

0
Galley