如何替換 Kotlin 中 String 中重複的 whitespace?


為了去除字串中的多餘空格,我們將使用 String 類的 replace() 函式以及 toRegex() 函式。要將所有連續的空格替換為單個空格“”,請將 replace() 函式與正則表示式“\s +”一起使用,該正則表示式與一個或多個空格字元匹配。

示例 – 移除 Kotlin 中的多餘空格

看一看以下示例——

fun main(args: Array<String>) {
   var myString = "Removing ex tra spa ce from String"
   println("Input String: 
" + myString)    // removing duplicate whitespace    println("
Extra whitespaces removed:
"    + myString.replace("\s+".toRegex(), " "))    // removing all the whitespaces    println("
After removing all the whitespaces:
"    + myString.replace("\s+".toRegex(), "")) }

輸出

它將生成以下輸出 -

Input String:
Removing ex tra spa ce from String

Extra whitespaces removed:
Removing ex tra spa ce from String

After removing all the whitespaces:
RemovingextraspacefromString

您可以使用正則表示式“\s{2,}”,該正則表示式與恰好兩個或兩個以上的空格字元相匹配。

fun main(args: Array<String>) {
   var myString = "Use Coding Ground to Compile and Execute Kotlin Codes"
   println("Input String: 
" + myString)    // removing consecutive double whitespaces    println("
After removing double whitespaces:
"    + myString.replace("\s{2,}".toRegex(), " ")) }

輸出

它將選取給定字串中的連續空格並用單個空格替換它們。

Input String:
Use Coding Ground to Compile and Execute Kotlin Codes

After removing double whitespaces:
Use Coding Ground to Compile and Execute Kotlin Codes

更新於:2022-03-16

4 千餘次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告