# 5 行 Kotlin 代碼實現自動給中文英文之間加入合適的空格


「有研究顯示,打字的時候不喜歡在中文和英文之間加空格的人,感情路都走得很辛苦,有七成的比例會在 34 歲的時候跟本身不愛的人結婚,而其他三成的人最後只能把遺產留給本身的貓。畢竟愛情跟書寫都須要適時地留白。與你們共勉之。」—— vinta/paranoid-auto-spacinggit

先看完整代碼:github

fun isLatin(c: Char) = c.toInt() < 256

fun allowSpace(c: Char) = c !in " ,。;「」:《》『』、[]()*_"

fun String.addSpace() = this.toCharArray().map { it.toString() }.reduce { acc, s ->
    if (isLatin(acc[acc.lastIndex]) != isLatin(s[0]) && allowSpace(s[0]) && allowSpace(acc[acc.lastIndex])) acc + " " + s  else acc + s
}
複製代碼

固然若是強行再減,代碼也能夠縮短成 1 行。bash

關於中英文之間在什麼狀況下加空格。能夠參考掘金這篇文章。 :譯文排版規則指北#空格函數

step01: 首先把目錄文字分解成單個字符串集合:

var stringList: List<String> = this.toCharArray().map { it.toString() }
複製代碼

map 操做符:返回一個每個元素根據給定的函數轉換所組成的 List。測試

step02: 使用 reduce 操做符將單個字符串拆分組合。

stringList.reduce { acc, s ->{ 處理 }
複製代碼

reduce 操做符:在從第一項到最後一項經過一個函數累計全部的元素。ui

step03: 判斷先後是否須要加空格

isLatin(c: Char) :判斷此字符是否爲拉丁符號(字母,數字,半角符號等)this

allowSpace(c: Char):是否容許有空格(中文全角符號兩邊不須要加空格)spa

先後字符分別爲中英文,而且中文字符不能爲全角符號。code

代碼實現 :ci

if (isLatin(acc[acc.lastIndex]) != isLatin(s[0]) 
    && allowSpace(s[0]) && allowSpace(acc[acc.lastIndex]))
複製代碼

若是知足條件則在字符之間加上空格:

return  acc + " " + s
複製代碼

相反的話保持原樣:

return  acc + s
複製代碼

step04: 使用 && 測試樣例:

var text = "在LeanCloud上,數據存儲是圍繞AVObject進行的。今天出去買菜花了5000元。"
text = text.addSpace()
println(text)
複製代碼

輸出爲:

在 LeanCloud 上,數據存儲是圍繞 AVObject 進行的。今天出去買菜花了 5000 元。

setp05: 彩蛋,一行代碼實現全部功能。

fun String.addSpace() = this.toCharArray().map { it.toString() }.reduce { acc, s -> if ((acc[acc.lastIndex].toInt() < 256 != s[0].toInt() < 256) && s[0] !in " ,。;「」:《》『』、[]()*_" && acc[acc.lastIndex] !in " ,。;「」:《》『』、[]()*_") acc + " " + s else acc + s }
複製代碼

關於我:微博簡書掘金Github

相關文章
相關標籤/搜索