English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à utiliser les expressions régulières en Java pour supprimer tous les espaces d'une chaîne donnée.
public class Whitespaces { public static void main(String[] args) { String sentence = "T his is b ett er! www. w"3codebox. com"; System.out.println("Original sentence: " + sentence); sentence = sentence.replaceAll("\\s", ""); System.out.println("After replacing and deleting spaces: " + sentence); } }
When running the program, the output is:
Original sentence: T his is b ett er!www. w3codebox. com After replacing and deleting spaces: Thisisbetter!fr.oldtoolbag.com
In the above program, we use the String's replaceAll() method to delete and replace all spaces in the string sentence.
We use the regular expression\\s to find all whitespace characters (tabs, spaces, newline characters, etc.) in the string. Then, we replace them with an empty string.