Android Code Snippet [B4X] Extract the first letter of a first and last name

Extracts the first letter of a first name and last name.
If you wish, you can extract the first letter of the first name and the full last name.

B4X:
    Log(GetNameLetter("ti-logistic"))
    Log(GetNameLetter("Aeric Poon"))
    Log(GetNameLetter("McFarland, Dave"))
    Log(GetNameLetter("A & W"))
    Log(GetNameLetter("Stewart & Andrew"))

B4X:
Public Sub GetNameLetter(Text As String) As String
    Dim Result As StringBuilder, Pattern As String = "(\w+).*\W+(\w+)$"
    Dim Matcher As Matcher = Regex.Matcher(Pattern, Text)
    Result.Initialize
    If Matcher.Find Then
        For i = 1 To Matcher.GroupCount
            Result.Append(Matcher.Group(i).SubString2(0,1))
        Next
    End If
    Result.ToString.ToUpperCase
End Sub

test:
1715840506264.png



Your comments are welcome
 
Last edited:

LucaMs

Expert
Licensed User
Longtime User
This one should work (not tested enough):
B4X:
Public Sub GetNameLetter(Text As String) As String
    Dim Result As StringBuilder
    Dim Words() As String
    Result.Initialize
    Words = Regex.Split("\s+", Text.Trim)
    For Each Word As String In Words
        Result.Append(Word.SubString2(0, 1))
    Next
    Return Result.ToString.ToUpperCase
End Sub
 

TILogistic

Expert
Licensed User
Longtime User
With this that does not work well:
B4X:
Log(GetNameLetter("Maria Grazia Cucinotta"))
The function should return MGC.

(Search the WEB if you don't know her ?)
Attrice nel film El Cartero di Pablo Neruda (cileno)
Actress in the film El Cartero by Pablo Neruda (Chilean)
Beautiful woman
???
 
Top