English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map collection

Java Set collection

Java entrée/sortie (I/O)

Reader Java/Writer

Autres sujets Java

Méthode et exemple d'utilisation de trim() String Java

Java String (string) methods

La méthode trim() de String Java retourne une chaîne qui supprime tous les espaces avant (début) et après (fin).

La syntaxe de la méthode trim() de la chaîne est :

string.trim()

Paramètres de trim()

  • La méthode trim() ne prend aucun paramètre

Retour de trim()

  • Retourne une chaîne sans espaces avant et après

  • Si il n'y a pas d'espaces au début ou à la fin, le retourne la chaîne d'origine.

Remarque :Dans la programmation, les espaces sont des caractères ou une série de caractères qui représentent des espaces horizontaux ou verticaux. Par exemple : les espaces, les caractères de retour chariot \n, les tabulations \t, les tabulations verticales \v, etc.

Exemple : trim() de chaîne Java

class Main {
  public static void main(String[] args) {
    String str1 = "     Apprendre   Java Programming ";
    String str2 = "Apprendre\nJava Programming\n\n   ";
    System.out.println(str1.trim());
    System.out.println(str2.trim());
  }
}

Résultat de la sortie

Apprendre Java Programming
Apprendre
Java Programming

In this case, str1.trim() returns

"Learn\t\tJava\tProgramming"

Similarly, str2.trim() returns

"Learn\nJava\n\n\tProgramming"

From the above example, it can be seen that the trim() method only removes leading and trailing spaces. It does not remove spaces that appear in the middle.

remove all whitespace characters

If necessaryremove all whitespace characters from the stringthen you canString replaceAll() methodused with appropriate regular expressions.

class Main {
  public static void main(String[] args) {
    String str1 = "Learn\nJava\n\n\t";
    String result;
    //Replace all whitespace characters with an empty string
    result = str1.replaceAll("\\s", "");
    System.out.println(result);  // LearnJava
  }
}

Java String (string) methods