Is there a way to get rid of accents and convert a whole string to regular letters?

前端 未结 12 2167
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 04:58

Is there a better way for getting rid of accents and making those letters regular apart from using String.replaceAll() method and replacing letters one by one?

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:19

    In case anyone is strugling to do this in kotlin, this code works like a charm. To avoid inconsistencies I also use .toUpperCase and Trim(). then i cast this function:

       fun stripAccents(s: String):String{
    
       if (s == null) {
          return "";
       }
    
    val chars: CharArray = s.toCharArray()
    
    var sb = StringBuilder(s)
    var cont: Int = 0
    
    while (chars.size > cont) {
        var c: kotlin.Char
        c = chars[cont]
        var c2:String = c.toString()
       //these are my needs, in case you need to convert other accents just Add new entries aqui
        c2 = c2.replace("Ã", "A")
        c2 = c2.replace("Õ", "O")
        c2 = c2.replace("Ç", "C")
        c2 = c2.replace("Á", "A")
        c2 = c2.replace("Ó", "O")
        c2 = c2.replace("Ê", "E")
        c2 = c2.replace("É", "E")
        c2 = c2.replace("Ú", "U")
    
        c = c2.single()
        sb.setCharAt(cont, c)
        cont++
    
    }
    
    return sb.toString()
    

    }

    to use these fun cast the code like this:

         var str: String
         str = editText.text.toString() //get the text from EditText
         str = str.toUpperCase().trim()
    
         str = stripAccents(str) //call the function
    

提交回复
热议问题