Removing space at end of string

aaronk

Well-Known Member
Licensed User
Longtime User
Hello,

I have a string and I want to know how to remove any spaces at the end of the string?

For Example:
If the string says 'this is a test '
then I want it to replace it with 'this is a test'
(removes the last 2 spaces from the string but must leave the spaces between the words)

Anyone able to help me out ?
 

aaronk

Well-Known Member
Licensed User
Longtime User
Just worked it out..

Incase anyone else wants to know, here is how I did it:

B4X:
dim MyString as string
   MyString = "this is a test  "
For i = 1 To MyString.Length 
      If MyString.EndsWith(" ") Then
            MyString = MyString.SubString2(0, MyString.Length -1)     
      End If
   Next
   msgbox(MyString,"") ' displays MyString (this is a test) without any spaces
 
Upvote 0

Stulish

Active Member
Licensed User
Longtime User
im not sure why you used a for/next loop as the following should work fine:

B4X:
Dim MyString,OutString As String
   MyString = "this is a test "
   If MyString.EndsWith(" ") Then MyString = MyString.SubString2(0,MyString.Length-1)
   Log("'" & MyString & "'")
    Msgbox(MyString,"") ' displays MyString (this is a test) without any spaces


or use trim (this removes leading and trailing spaces :

B4X:
Dim MyString As String
   MyString = " this is a test    "
   MyString = MyString.Trim
   Msgbox(MyString,"") ' displays MyString (this is a test) without any leading/trailing spaces


alternativley is you could have more than one trailing space but you want to keep any leading spaces:

B4X:
Dim MyString,OutString As String, i As Int 
   MyString = " this is a test     "
   i = MyString.Length -1 ' i equals the last character position of the string
   Do While MyString.CharAt(i)=" " 'if the charater is A space then
      OutString = MyString.SubString2(0, i) 'make the output string equal the string without the last character
      i=i-1
   Loop
   If OutString<>"" Then MyString = OutString 
   Log("'" & MyString & "'")
    Msgbox(MyString,"") ' displays MyString (this is a test) without any spaces

this counts back from the end of the string until it reaches its first character.

hope it is useful

Regards

Stu
 
Last edited:
Upvote 0
Top