Android Question String with readable characters only

GuyBooth

Active Member
Licensed User
Longtime User
Does anyone have an elegant way to remove unreadable characters from a string?
I have one that looks like this
TITLE: MJ૚c�����P�[���(�ō"V���N�

and as an example for this one I need to trim it down to TITLE: MJcP[("VN.
If I lose the [( and " I can live with that too.
 

RB Smissaert

Well-Known Member
Licensed User
Longtime User
Does anyone have an elegant way to remove unreadable characters from a string?
I have one that looks like this
TITLE: MJ૚c�����P�[���(�ō"V���N�

and as an example for this one I need to trim it down to TITLE: MJcP[("VN.
If I lose the [( and " I can live with that too.

Something like this should work:

B4X:
Sub ClearUnreadable(str As String) As String
 Dim i As Int
 Dim n As Int
 Dim arrBytes() As Byte
 arrBytes = str.GetBytes("UTF8")
 Dim arrBytes2(arrBytes.Length) As Byte
 For i = 0 To arrBytes.Length - 1
  If arrBytes(i) > 0 Then
   arrBytes2(n) = arrBytes(i)
   n = n + 1
  End If
 Next
 Return BC.StringFromBytes(arrBytes2, "UTF8").SubString2(0, n)
End Sub

BC is the ByteConverter library

RBS
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
MJcP[("VN.
And if you want to obtain this: MJcP[("VN, you can still use Regex function without reverting to any additional libraries:
B4X:
Dim MyString As String = $"MJ૚c�����P�[���(�ō"V���N�"$
Log( Regex.Replace($"[^a-zA-Z0-9-\[\(${QUOTE}]"$,MyString,"") )  'displays: MJcP[("VN
 
Upvote 0

GuyBooth

Active Member
Licensed User
Longtime User
And if you want to obtain this: MJcP[("VN, you can still use Regex function without reverting to any additional libraries:
B4X:
Dim MyString As String = $"MJ૚c�����P�[���(�ō"V���N�"$
Log( Regex.Replace($"[^a-zA-Z0-9-\[\(${QUOTE}]"$,MyString,"") )  'displays: MJcP[("VN

Thank you! I could never figure out Regex :(
But I added \s to keep spaces:
Regex.Replace($"[^a-zA-Z0-9-\s\[\(${QUOTE}]"$,MyString,"")
 
Upvote 0

GuyBooth

Active Member
Licensed User
Longtime User
Final version:
Regex.Replace($"[^a-zA-Z0-9-\s\[\(\)'"]"$,MyString,"")

The smartstring Mahares used (great tip!) allows me to use a simple " instead of ${QUOTE}. I added the other bracket ( ) ), and the single quote.
 
Upvote 0
Top