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?

全角、半角の判別方法

Last updated at Posted at 2024-09-20

Kotlinでの全角、半角の変換方法をメモする。

Normalizeを使用した方法。全角半角などの表記揺れを統一するために使用するもので全角半角変換目的ではあまり使用できない。

normalize("①11", Normalizer.Form.NFKC)
// 111
normalize("コンニチハ", Normalizer.Form.NFKC)
// コンニチハ
normalize("コンニチハ", Normalizer.Form.NFKC)
// コンニチハ
normalize("Hello", Normalizer.Form.NFKC)
// Hello
normalize("Hello", Normalizer.Form.NFKC)
// Hello

Replaceで1つ1つの変換先を登録する。確実に意図した文字変換が可能だが全て登録するのは手間がかかる。

fun convertString(target : String ):String
{
    var str : String

    str = target.replace("A","A" ).replace("B","B" ).replace("C","C" ).replace("D","D" ).replace("E","E" ).replace("F","F" ).replace("G","G" ).replace("H","H" ).replace("I","I" ).replace("J","J" ).replace("K","K" ).replace("L","L" ).replace("M","M" ).replace("N","N" ).replace("O","O" ).replace("P","P" ).replace("Q","Q" ).replace("R","R" ).replace("S","S" ).replace("T","T" ).replace("U","U" ).replace("V","V" ).replace("W","W" ).replace("X","X" ).replace("Y","Y" ).replace("Z","Z" ) 

    str = str.replace("a","a" ).replace("b","b" ).replace("c","c" ).replace("d","d" ).replace("e","e" ).replace("f","f" ).replace("g","g" ).replace("h","h" ).replace("i","i" ).replace("j","j" ).replace("k","k" ).replace("l","l" ).replace("m","m" ).replace("n","n" ).replace("o","o" ).replace("p","p" ).replace("q","q" ).replace("r","r" ).replace("s","s" ).replace("t","t" ).replace("u","u" ).replace("v","v" ).replace("w","w" ).replace("x","x" ).replace("y","y" ).replace("z","z" )

    str = str.replace("0","0" ).replace("1","1" ).replace("2","2" ).replace("3","3" ).replace("4","4" ).replace("5","5" ).replace("6","6" ).replace("7","7" ).replace("8","8" ).replace("9","9" )
    
    return str 
}
println(convertString("0123abc"))
// 0123abc

toByteArray()を使用すれば半角、全角の文字を判別することが可能。以下のコードは全角文字が1つでも含まれていた場合にtureとなる。

"Good morning!".any { it.toString().toByteArray(Charsets.UTF_8).size > 1 }
// false
"おはようございます!".any { it.toString().toByteArray(Charsets.UTF_8).size > 1 }
// true
"123456".any { it.toString().toByteArray(Charsets.UTF_8).size > 1 }
// false

参考

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?