trim function

stefanobusetto

Active Member
Licensed User
Longtime User
i think the trim function doesn't work properly
the function should trim the spaces at the end of a string
but it also trims the characters with ascii code below 32
here is the sample code:
B4X:
Dim s As String
Dim t As String
Dim j As Int

s = "" 
For j = 1 To 10
    s = s & Chr(j)
Next
t = s.Trim

Log ( "source string" )
For j = 0 To s.Length - 1
    Log ( "index = " & j & " ascii = " & Asc ( s.CharAt(j) ) )
Next

Log ( "trimmed string" )
For j = 0 To t.Length - 1
    Log ( "index = " & j & " ascii = " & Asc ( t.CharAt(j) ) )
Next
program output:
source string
index = 0 ascii = 1
index = 1 ascii = 2
index = 2 ascii = 3
index = 3 ascii = 4
index = 4 ascii = 5
index = 5 ascii = 6
index = 6 ascii = 7
index = 7 ascii = 8
index = 8 ascii = 9
index = 9 ascii = 10
trimmed string
(no output)

tanks
 
Last edited by a moderator:

stefanobusetto

Active Member
Licensed User
Longtime User
very tanks anyway

the spaces at the end i mean
i did it at the end

Do While s.EndsWith ( " " )
s = s.SubString2 ( 0 , s.Length - 1 )
Loop
 

Jost aus Soest

Active Member
Licensed User
Longtime User
Do While s.EndsWith ( " " )
s = s.SubString2 ( 0 , s.Length - 1 )
Loop

I would prefer using this function:
B4X:
Sub RTrimSpaces(s As String) As String

  Dim i As Int

  For i = s.Length - 1 To 0 Step -1
    If s.CharAt(i) <> " " Then Exit
  Next'i
  Return s.SubString2(0, i + 1)

End Sub
Advantage: It's faster and uses less ressources, because this sub builds a new string only one time.
 

nicodh

Member
Licensed User
Longtime User
Hi Erel, I'm trying to use trim, and it seems it does not work cleaning white spaces.

Example:
Dim test As String
test="yaw Deadband"
test=test.ToLowerCase ' test becomes "yaw deadband"
test=test.Trim 'test still is yaw deadband when it should be yawdeadband

Am I right?
 

nicodh

Member
Licensed User
Longtime User
Reading your comment just realize what it meant, and it was my mistake. I use replace for doing that.

I should read better the help... Sometimes i feel like a dork, and the rest of the time I am.

Thanks a lot!
 

ciarli

Member
Licensed User
Longtime User
I'd like to have three functions: ltrim for the left spaces, rtrim for the right spaces and trim for all spaces, also the internal.
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…