0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Kotlin】全角なら2、半角なら1で文字数を取得する

Posted at

実践

正規表現を使用して全角と半角を判定します。

  private val HALF_WIDTH_PATTERN = Regex("[a-zA-Z0-9ヲ-゚]")

  private fun getPrintableLength(str: String): Int {
    var width = 0
    for (c in str) {
        val s = c.toString()
        // Regex.matcher -> Regex.matches に変更
        width += if (HALF_WIDTH_PATTERN.matches(s)) {
            1 // 半角
        } else {
            2 // 全角
        }
    }
    return width
  }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?