Android Question How to remove accents from text?

Erel

B4X founder
Staff member
Licensed User
Longtime User
This code will remove the accents:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Log(RemoveAccents("áóúñéí"))
End Sub

Sub RemoveAccents(s As String) As String
   Dim normalizer As JavaObject
   normalizer.InitializeStatic("java.text.Normalizer")
   Dim n As String = normalizer.RunMethod("normalize", Array As Object(s, "NFD"))
   Dim sb As StringBuilder
   sb.Initialize
   For i = 0 To n.Length - 1
     If Regex.IsMatch("\p{InCombiningDiacriticalMarks}", n.CharAt(i)) = False  Then
       sb.Append(n.CharAt(i))
     End If
   Next
   Return sb.ToString
End Sub
 
Last edited:
Upvote 0

GeoT

Active Member
Licensed User
Longtime User
According to Google's Gemini, the code provided by Erel is not particularly efficient and works primarily with the Latin alphabet (used in Spanish, English, French, Portuguese, German, etc.), but it has serious limitations with other writing systems.

Best ways:
  • Broader (includes characters from other alphabets in addition to Latin/standard alphabets)
B4X:
Public Sub RemoveAccents(s As String) As String
    If s = "" Then Return ""
    
    Dim staticNormalizer As JavaObject
    staticNormalizer.InitializeStatic("java.text.Normalizer")
    
    Dim nfdForm As JavaObject
    nfdForm.InitializeStatic("java.text.Normalizer$Form")
    
    Dim normalized As String = staticNormalizer.RunMethod("normalize", Array(s, nfdForm.GetField("NFD")))
    Dim joStr As JavaObject = normalized
    
    Dim cleanStr As String = joStr.RunMethod("replaceAll", Array("\p{M}+", ""))    ' Removes all accents in a single C++ step
    
'    Return cleanStr.Trim.ToLowerCase           ' To process data for a search engine or index where you need to force everything to lowercase and remove leading or trailing spaces
    Return cleanStr                             ' If the original text format is respected (capital letters, spaces before and after)
End Sub

  • Focused on Latin/standard alphabets
B4X:
Public Sub RemoveAccents2(s As String) As String
    If s = "" Then Return ""

    ' 1. Get the NFD enumeration
    Dim nfdForm As JavaObject
    nfdForm.InitializeStatic("java.text.Normalizer$Form")

    ' 2. Normalize the string
    Dim normalizer As JavaObject
    normalizer.InitializeStatic("java.text.Normalizer")
    Dim normalized As JavaObject = normalizer.RunMethod("normalize", Array(s, nfdForm.GetField("NFD")))

    ' 3. Replace diacritics (SINGLE BAR '\' IS USED)
    Dim result As String = normalized.RunMethod("replaceAll", Array("\p{InCombiningDiacriticalMarks}+", ""))

'    Return result.Trim.ToLowerCase        ' To process data for a search engine or index where you need to force everything to lowercase and remove leading or trailing spaces
   Return result                           ' If the original text format is respected (capital letters, spaces before and after)
End Sub
 
Upvote 0
Top