Kotlin 从字符串中删除所有空格的程序

Example: Program to Remove All Whitespaces

fun main(args: Array<String>) {
    var sentence = "T    his is b  ett     er."
    println("Original sentence: $sentence")

    sentence = sentence.replace("\\s".toRegex(), "")
    println("After replacement: $sentence")
}

运行程序后,输出将是

Original sentence: T    his is b  ett     er.
After replacement: Thisisbetter.

In the above program, we use String's replace() method to remove and replace the whitespaces in the string sentence.

We've used regular expression \\s that finds all white space characters (tabs, spaces, new line character, etc.) in the string. Then, we replace it with "" (empty string literal).

Here's the equivalent Java code: Java program to remove all whitespaces

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战