English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
L'expression régulière "\\s" correspond aux espaces dans la chaîne. LareplaceAll()
La méthode accepte une chaîne de caractères et remplace les caractères correspondants avec une chaîne donnée. Pour supprimer tous les espaces blancs de la chaîne d'entrée, passez la chaîne mentionnée précédemment et une chaîne vide en tant qu'entrée à appelerreplaceAll()méthode.
public class RemovingWhiteSpaces { public static void main( String args[] ) { String input = "Hi welcome to w3codebox"; String regex = "\\s"; String result = input.replaceAll(regex, ""); System.out.println("Result: "+result); } }
Output Result
Résultat: Hiwelcometow3codebox
De même,appendReplacement()La méthode accepte un tampon de chaîne et une chaîne de remplacement, et utilise la chaîne de remplacement fournie pour ajouter les caractères correspondants et les ajouter au tampon de chaîne.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemovingWhiteSpaces { public static void main( String args[] ) { Scanner sc = new Scanner(System.in); System.out.println("Entrez une chaîne d'entrée: "); String input = sc.nextLine(); String regex = "\\s"; String constants = ""; System.out.println("Chaine d'entrée: \n"+input); //Créer un objet modèle Pattern pattern = Pattern.compile(regex); //Match the compiled pattern in the string Matcher matcher = pattern.matcher(input); //Create an empty string buffer StringBuffer sb = new StringBuffer(); while (matcher.find()) { constants = constants+matcher.group(); matcher.appendReplacement(sb, ""); } matcher.appendTail(sb); System.out.println("Result: "+ sb.toString()+constants ); } }
Output Result
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
public class Just { public static void main(String args[]) { String input = "This is a sample text with spaces"; String[] str = input.split(" "); String result = ""; for(int i = 0; i < str.length; i++) { result = result+str[i]; } System.out.println("Result: "+result); } }
Output Result
Result: This is a sample text with spaces