Android Question [Solved]How to code function CharArrayToString()

Theera

Well-Known Member
Licensed User
Longtime User
Refer to Daestrum's a part of code
B4X:
Public Sub CharArrayToString(YourCharArray As A Char()) As String
    Dim b() As Char = YourCharArray
    Dim d As String
    d =  d.As(JavaObject).RunMethod("valueOf",Array(b))
    Return d
End Sub
 
Last edited:
Solution
You must use the builtin library "ByteConverter"

B4X:
Public Sub CharArrayToString(YourCharArray() As Char) As String
    Dim bc As ByteConverter
    Return bc.FromChars(YourCharArray)
End Sub

Public Sub StringToCharArray(YourString As String) As Char()
    Dim bc As ByteConverter
    Return bc.ToChars(YourString)
End Sub

Example of usage:
    Dim myString As String = "This is a string"   
    Log($"myString:${myString}"$)

    Dim    myCharArray() As Char = StringToCharArray(myString)
    Log($"myCharArray:${myCharArray}"$)

    Dim AndNowAsStringAgain As String = CharArrayToString(myCharArray)
    Log($"AndNowAsStringAgain:${AndNowAsStringAgain}"$)

Resulting logs:
myString:This is a string
myCharArray:[C@2ef9b8bc
AndNowAsStringAgain:This...

knutf

Active Member
Licensed User
Longtime User
You must use the builtin library "ByteConverter"

B4X:
Public Sub CharArrayToString(YourCharArray() As Char) As String
    Dim bc As ByteConverter
    Return bc.FromChars(YourCharArray)
End Sub

Public Sub StringToCharArray(YourString As String) As Char()
    Dim bc As ByteConverter
    Return bc.ToChars(YourString)
End Sub

Example of usage:
    Dim myString As String = "This is a string"   
    Log($"myString:${myString}"$)

    Dim    myCharArray() As Char = StringToCharArray(myString)
    Log($"myCharArray:${myCharArray}"$)

    Dim AndNowAsStringAgain As String = CharArrayToString(myCharArray)
    Log($"AndNowAsStringAgain:${AndNowAsStringAgain}"$)

Resulting logs:
myString:This is a string
myCharArray:[C@2ef9b8bc
AndNowAsStringAgain:This is a string

But I would not have made subs for this conversion, I would rather done like this:
B4X:
    Dim bc As ByteConverter

    Dim myString As String = "This is a string"
    Log($"myString:${myString}"$)

    Dim    myCharArray() As Char = bc.ToChars(myString)
    Log($"myCharArray:${myCharArray}"$)

    Dim AndNowAsStringAgain As String = bc.FromChars(myCharArray)
    Log($"AndNowAsStringAgain:${AndNowAsStringAgain}"$)
 
Upvote 0
Solution
Top