B4A Library String Functions

Updated: 3/14/2014 - Version 1.05, This new version has 14 new functions/commands. Please report any issues. The new functions/commands are underlined and listed below in the updated docs.

Updated: 9/19/2013 - Version 1.04, Corrected an error in the Mid() function when retrieving the last character.

Updated: 8/28/2013 - Version 1.03, Added code to stop OutOfBounds error on the Mid Function. This would happen when an invalid index was passed to the function. Also corrected a bug that was in the DayOfMonth Function in versions prior to 1.02.

Updated: 4/5/2013 Added new date functions and a simple Encrypt and Decrypt Function. NOTE: A few older Functions were renamed.

StringFunctions use function names that are closer to the VB commands and may help beginners when they start programming in B4A. I wrote them for that reason when I started. These functions use to be in a code module but have now been converted to a Library. This has the new inline syntax and help as you start to type the command.

Requires B4A 2.5 or Higher
Copy the StringFunctions.jar and StringFunctions.xml to the Extra Libraries folder.


Be sure to DIM the Lib object like Below. You can use any variable name in place of sf in the Example below.
B4X:
Sub Globals
   Dim sf As StringFunctions
   sf.Initialize
End Sub

StringFunctions Version 1.05

  • AsciiCodes
    Displays a MessageBox with all Characters and their ASCII codes.
  • AddSpaces (HowMany As Int) As String
    Returns a string of spaces. The number returned is set by HowMany.
  • At (YourString As String, SearchFor As String))
    Returns the position of the SearchFor within YourString.
  • CurrentWeek (MyDate As String) As Int
    Returns the number of the current week, 1-52 from the date passed to MyDate.
  • DayOfMonth (MyDate As ) As Int
    Returns the day of the month like 1-31, from the date passed to MyDate.
  • Decrypt (YourText As String) As String
    Converts an encrypted string of text to readable format, no key is needed.
  • Empty (StringText As String) As Boolean
    Test to see if the string is empty and returns True if it is, otherwise returns False.
  • Encrypt (YourText As String) As String
    Converts a string of text to simple encryption, no Key is needed.
  • EraseData
    This will erase all data saved with the SaveData function stored in the
    temporary vault.
  • FileExist (PathAndFileName As String) As Boolean
    Returns True if the filename passed does exist, otherwise returns False.
    Be sure to include the path like:
    If FileExist("/mnt/sdcard/mydata.dat") Then MsgBox("Yes", "The Answer")
  • GetData (Key As Object) As Object
    Gets data from the temporary vault.
    EditText1.Text = SF.GetData("EnteredName")
    The Key is case sensitive.
  • InString (YourString As String, SearchFor As String))
    Returns the position of the SearchFor within YourString.
  • IsEmpty (StringText As String) As Boolean
    Test to see if the string is empty and returns True if it is, otherwise returns False.
  • Left (StringText As String, Length As Long) As String
    Returns the Left portion of a string with the number of characters passed
    in Length.
  • Len (StringText As String) As Long
    Returns the length of the string.
  • ListToString (YourList As List, Sorted As Boolean, Ascending As Boolean) As String
    Converts a List object to a String.
  • ListToStringArray (YourList As List, Sorted As Boolean, Ascending As Boolean) As String()
    Converts a List object to a String Array.
  • Lower (StringText As String) As String
    Returns the string converted to Lowercase characters.
  • Ltrim (StringText As String) As String
    Returns a new string with the leading spaces removed.
  • MB (Message As String)
    Same as MsgBox but only needs one parameter.
  • Mid (StringText As String, Start As Int, Length As Int) As String
    Returns the a new String for how ever many characters passed in Length from
    a starting position passed in Start.
    Example:
    Mid("This is a long line of text", 5, 2)
    In this example the function will Return: "is"
  • MidExtract (StringText As String, Start As String, EndAt As String) As String
    Used to extract text from a string between to other blocks of text.
    Ans = MidExtract("Dr. Jim Joe Brown", "Jim", "Brown") 'Returns: Joe
    Ans = MidExtract("Dr. Jim [Joe] Brown", "[", "]") 'Returns: Joe
  • MidS (StringText As String, StartAt As Int) As String
    Works like the Mid$ function in Visual Basic.
  • Month (MyDate As String) As Int
    Returns the number of the current month 1-12 as Int type, from the date passed to MyDate.
  • MonthName (MyDate As String) As String
    Returns the Name the current month as a String like January, etc., from the date passed to MyDate.
  • NewDate (DatePassed As String, HowManyDays As Int) As String
    Returns a new date adding or subtracting HowManyDays. HowManyDays can be positive or
    negative numbers.
  • NumOfDaysBetween (CurrentDate As String, OtherDate As String) As Int
    Returns the numbers of days passed between the two dates passed.
  • Pad (Text As String, PadWith As String, Length As Int, Post As Boolean) As String
    Used to pad a string with a selected character. If Post = True the padding will follow
    any text in the string, if Post = False, the padding will be before the text. Length is
    the total length for the padded string. PadWith is the selected character to use for the
    padding.
    SF.Pad("Jimmy Joe", "*", 20, True) 'Returns "Jimmy Joe***********"
  • Proper (StringText As String) As String
    Returns the string in proper format.
    Example:
    MyText = "jim joe brown"
    MyText = SF.Proper(Mytext)
    This function will return: "Jim Joe Brown"
  • Replicate (mChar As String, Times As Int) As String
    Repeats any character passed, a selected number of Times.
  • Right (StringText As String, Length As Long) As String
    Returns the Right portion of a string with the number of characters passed
    in Length.
  • RndChrGen (StringLength As Int, CharacterType As Int) As String
    Returns a string of ramdom characters with a length specified by StringLength. CharacterType tells
    the function what type of characters to return.
    CharacterType = 0 for Upper and Lower case
    CharacterType = 1 for Upper case only
    CharacterType = 2 for Lower case only
  • Rtrim (StringText As String) As String
    Returns a new string with the trailing spaces removed.
  • SaveData (Key As Object, Data As Object)
    Save data passed in a temporary file.
    SF.SaveData("ScreenTitle", MyVar)
    or
    SF.SaveData("EnteredName", EditText1.Text)
  • ScrInfo ( As Pect) As Int
    Returns information about the devices screen. You can pass these parameters:
    Pass "W" for Width
    Pass "H" for Height
    Pass "S" for Scale
    Pass "D" for DPI
    Call like: SF.ScrInfo("W")
  • SearchDate (Date1 As String, Date2 As String, DateRange As Int) As Boolean
    Returns True if the Date1 and the Date2 are within x Days(DateRange) of each other.
    Pass the dates as Strings.
    Example:
    SearchDate("03/01/2013", "02/15/2013", 30)
  • Split (CurrentString As String, Split_At_Delimiter As String) As List
    Returns a LIST of items from the string split at the Delimiter.
    EXAMPLE:
    Dim ANS As List
    ANS = SF.Split("This is a test string.", " ")
  • SplitGetWord (CurrentString As String, Split_At_Delimiter As String, GetElement As Int) As String
    Returns just the one element selected with GetElement from the string.
    EXAMPLE:
    ANS = SF.SplitGetWord("This is a test string.", " ", 2)
    In this example the function will Return: "is"
  • StrArraySort (StringArray() As String, Ascending As Boolean) As String()
    Used to sort a String Array. Sort will be in Ascending order if Ascending = True.
  • StringArrayToList (StringArray() As String, Sorted As Boolean, Ascending As Boolean) As List
    Converts a String Array to a List object.
  • StringToList (StringText As String, Sorted As Boolean, Ascending As Boolean) As List
    Convert a String to a List object. This will split the string between words.
  • Stuff (CurrentText As String, InsertInString As String, RemoveFromString As String) As String
    Used to replace text in a string with new text.
    Example:
    MyText = "I will tell you that joe is a good friend!"
    MyText = SF.Stuff(MyText, "Joe Brown", "joe")
    This function will return: "I will tell you that Joe Brown is a good friend!"
  • Today () As String
    Returns the devices date.
  • Trim (Text As String) As String
    Returns a new string with leading and trailing spaces removed.
  • Upper (StringText As String) As String
    Returns the string converted to Uppercase characters.
  • Val (StringText As String) As Double
    Returns the numerical value of a string. If the string contains now value it returns 0.
  • ValidDate (ChkDate As ) As Boolean
    Returns True if the date passed is a Valid date.
  • WeekDay (MyDate As String) As String
    Returns the number of the day of the week 1-7 as a String, from the date passed to MyDate.
  • WeekName (MyDate As String) As String
    Returns the name of the day of the week like Sunday, Monday, etc., from the date passed to MyDate.
  • Year (MyDate As String) As String
    Returns the year of the date passed in MyDate.
    Example:
    SF.Year("01/01/2013") returns "2013"
  • getSDCardPath () As String
    Returns external/physical SD Card directory. This function may not return the correct store
    on an Android OS above 4.1. This is due to changes made to the OS system in the newer versions.
    Returns "", if the store can not be read.
  • iif (Value1 As String, Value2 As String, Value3 As String) As String
    This is a single line if conditional test. If Value1 is true, Value2 is returned, otherwise
    Value3 will be returned. Works with strings and booleans.
    Example:
    MsgBox(iif("Bob"="Jim", "They are the same", "They are not the same"), "The Answer")
    or
    MyBoolean = iif(FirstTime = True, StartMyService = True, StartMyService = False)
 

Attachments

  • StringFunctions 1.0.zip
    5.8 KB · Views: 2,216
  • StringFunctions 1.01.zip
    7.3 KB · Views: 1,942
  • StringFunctions 1.03.zip
    7.4 KB · Views: 1,242
  • StringFunctions 1.04.zip
    7.6 KB · Views: 2,540
  • StringFunctions 1.05.zip
    10.6 KB · Views: 8,510
Last edited:

JonPM

Well-Known Member
Licensed User
Longtime User
Recently upgraded to B4A 1.8 and now when I compile apps created pre-1.8 I get error "Error description: Sub Process_Globals is missing." in this code module. So I added it and it works fine now...
 

Theera

Well-Known Member
Licensed User
Longtime User
Pls add this function: Instr(Text as string,Token as string) as int

Thank you for developed many fuction for manage string . Now I 'm looking for Instr() function Please help me
Best Regards
Theera

Hello All,

*** Just Added These Three New Functions: August 25th, 2011 - 1.10pm

s.Proper() – Example: converts “jerry smith” to “Jerry Smith” or "ms. betty sue smith" to "Ms. Betty Sue Smith"
s.Lower()
s.Upper()

*** Just Added These Three New Functions: July 28th, 2011 - 12.27am

s.Space()
s.RndChrGen() - Generate random characters to fill Edit.Text, etc.
s.Exist()

*** Just Added These Two New Functions: July 24th, 2011 - 2.27am

s.Empty()
s.iif() - (Immediate If - very useful)
Example: MyVar = s.iif(File.ExternalWritable, File.DirRootExternal, File.DirInternal)

I have now been writing in B4A for just over three weeks. Each day I learn something new and how powerful it is! But, at first I was lost and did not know how flexable it is but was still missing some string functions I used all the time in VB and others like Visual Fox. I have put together a sample of some UDFs I wrote and wanted to share them as so many others here have done! I hope it is useful for someone. The new functions are listed below:

s.At()
s.Left()
s.Len()
s.Ltrim()
s.Mid()
s.Right()
s.Rtrim()
s.Stuff()
s.Trim()
s.Val()



Thanks,

Margret
 

rbsoft

Active Member
Licensed User
Longtime User
B4X:
Sub InStr(StrVar As String,SearchStr As String)As Long 
   Dim x As Long 
   
   x = StrVar.IndexOf(SearchStr)
   Return x
End Sub


Rolf
 

Theera

Well-Known Member
Licensed User
Longtime User
Help me please

B4X:
Sub InStr(StrVar As String,SearchStr As String)As Long 
   Dim x As Long 
   
   x = StrVar.IndexOf(SearchStr)
   Return x
End Sub


Rolf

Thank You Rbsoft,for help and now I have question how to use s.bas file ? I have added s.file in program b4a already. I need use function in my program. But have error . This is
Compiling Code
Error parsing program
Error description:Sub Process_Globals is missing

P.S.
I created new function in your s.bas file. This is my function
Sub StrCutTokenStrAll(Passedstring As String,TokenStr As String) As String
Do Until Instr(Passedstring, TokenStr) = 0
Passedstring = s.Left(Passedstring, s.Instr(Passedstring, TokenStr) - 1) & s.Mid(Passedstring, s.Instr(Passedstring, TokenStr) + 1, s.Len(Passedstring) - s.Instr(Passedstring, TokenStr))
Loop
Return Passedstring
End Sub

I use check condition is s.StrCutTokenStrAll("This is a book"," ")=s.StrCutTokenStrAll("Thisisabook"," ") return true
 
Last edited:

rbsoft

Active Member
Licensed User
Longtime User
Exactly. If you add a new code module in B4A you always will find this code at the beginning of the code:

B4X:
'Code module
'Subs in this code module will be accessible from all modules.
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub

Just add this the code module (s.bas) and you can call the functions without problems from other modules. Example:

B4X:
Str1 = "abcdefgh"
Str2 = "c"
x = InStr(Str1,Str2)

'Returns 3

Rolf
 

rbsoft

Active Member
Licensed User
Longtime User
P.S.
I created new function in your s.bas file. This is my function
Sub StrCutTokenStrAll(Passedstring As String,TokenStr As String) As String
Do Until Instr(Passedstring, TokenStr) = 0
Passedstring = s.Left(Passedstring, s.Instr(Passedstring, TokenStr) - 1) & s.Mid(Passedstring, s.Instr(Passedstring, TokenStr) + 1, s.Len(Passedstring) - s.Instr(Passedstring, TokenStr))
Loop
Return Passedstring
End Sub

There is no need to refer to s.bas if your sub is part of that code module. You need this reference only if you are accessing a subin s.bas from another module. Your Sub should look like this:

B4X:
Sub StrCutTokenStrAll(Passedstring As String,TokenStr As String) As String
   Do Until Instr(Passedstring, TokenStr) = 0
   Passedstring = Left(Passedstring, Instr(Passedstring, TokenStr) - 1) & _
      Mid(Passedstring, Instr(Passedstring, TokenStr) + 1, Len(Passedstring) - _
      Instr(Passedstring, TokenStr))
   Loop
   Return Passedstring
End Sub

You would call your sub then from another module like this:

B4X:
t = s.StrCutTokenStrAll(PassedStr, TokenStr)

Rolf
 

Theera

Well-Known Member
Licensed User
Longtime User
@Theera:
Read the error decription: Sub Process_Globals is missing

You need a Process_Globals sub, even if it's empty!

Hi Jost aus Soest,
My app still has Sub Process_Globals already. I don't delete it. Please tell me
how I do continue in Sub Process_Globals.
Best Regards
Theera
 

Theera

Well-Known Member
Licensed User
Longtime User
There is no need to refer to s.bas if your sub is part of that code module. You need this reference only if you are accessing a subin s.bas from another module. Your Sub should look like this:

B4X:
Sub StrCutTokenStrAll(Passedstring As String,TokenStr As String) As String
   Do Until Instr(Passedstring, TokenStr) = 0
   Passedstring = Left(Passedstring, Instr(Passedstring, TokenStr) - 1) & _
      Mid(Passedstring, Instr(Passedstring, TokenStr) + 1, Len(Passedstring) - _
      Instr(Passedstring, TokenStr))
   Loop
   Return Passedstring
End Sub

You would call your sub then from another module like this:

B4X:
t = s.StrCutTokenStrAll(PassedStr, TokenStr)

Rolf

Thank you RbSoft,I think you answer me while I asking.
 

Theera

Well-Known Member
Licensed User
Longtime User
Thank you RbSoft,I think you answer me while I asking.

Hi Roft (RbSoft),
I still have the same error. I use B4A v1.9 ,please help again
Best Regards
Theera
 

Theera

Well-Known Member
Licensed User
Longtime User
Hi Rolf,
I think your instr() is unlike as same as instr() from VB6.0 that use 3 variables.
Best Regards
Theera

B4X:
Sub InStr(StrVar As String,SearchStr As String)As Long 
   Dim x As Long 
   
   x = StrVar.IndexOf(SearchStr)
   Return x
End Sub


Rolf
 

rbsoft

Active Member
Licensed User
Longtime User
That is right. I left out the first parameter (StartPos) which I never used. It is optional in VB and PB. This InStr always starts to search from the beginning of the string.

Rolf
 

rbsoft

Active Member
Licensed User
Longtime User
If you need that parameter StartPos then the Sub should be like this;

B4X:
Sub InStr(StartPos As Long, StrVar As String,SearchStr As String)As Long 
    Dim x As Long 
    
   x = StrVar.IndexOf2(SearchStr,StartPos)
    Return x
End Sub

Rolf
 

Theera

Well-Known Member
Licensed User
Longtime User
Hi Margret and Roft,
I have 2 function about manage string in VB 6.0 ,I need use in B4A . I cann't. Please help me to correct them I tried them ,have always error. this my code:

Sub StrCutTokenStrAll(Passedstring As String,TokenStr As String) As String
'This function to check 2 string be same data (i.e. "Book1" = "Book 1" )

Do Until InStr(Passedstring, TokenStr) = 0
Passedstring = Left(Passedstring, InStr(Passedstring, TokenStr) - 1) & Mid(Passedstring, InStr(Passedstring, TokenStr) + 1, Len(Passedstring) - InStr(Passedstring, TokenStr))
Loop
Return Passedstring
End Sub

Sub GetWord( StrVar As String,token As String, Nth As Int) As String
' This function returns the Nth token in a string
' Ex. msgbox GetWord("This is a test.", " ", 2) return "is"

Dim i As Int
Dim p As Int
Dim R As Int
Dim TargetStr As String
'*****************
TargetStr = " "
For i = 1 To Len(StrVar)
If Mid(StrVar, i, 1) = " " Then
If Mid(StrVar, i - 1, 1) <> " " Then
TargetStr = TargetStr + Mid(StrVar, i, 1)
End If
Else
TargetStr = TargetStr + Mid(StrVar, i, 1)
End If
Next
StrVar = Trim(TargetStr)

If Nth < 1 Then
Return ""
Exit
End If

R = 0
For i = 1 To Nth
p = R
R = InStr( p + 1,StrVar,token)
If R = 0 Then
If i = Nth Then
Return Mid(StrVar, p + 1, Len(StrVar) - p)
Else
Return ""
End If
Exit
End If
Next
Return Mid(StrVar, p + 1, R - p - 1)
End Sub



Hello All,

*** Just Added These New Functions: April 6th, 2012 - 10.00pm

Attached to Bottom of This Post: Version 1.2




Corrected for B4A version 1.9

B4X:
AsciiCodes(),  SearchDate(),  DateNew(),  DateNOD(),  Date(),  Split(),  InStr(),  MB(),  ValidDate()
   
AsciiCodes - 'Displays an dialog showing all the Ascii Codes
Date - 'returns the current system date
SearchDate("04/06/2012", "04/14/2012", 30) - 'true means the dates passed are within (x) days of each other, pass x as 3rd parameter
DateNew("02/12/2012", 90) - 'returns a new date 90 days later, 2nd parameter can be + or - number
DateNOD("04/06/2012", "12/12/2011") - 'show the days passed between dates passed
ValidDate("13/12/2012") - 'returns true if you pass a valid date
InStr("Where is me at", "me") - 'shows the location of 2nd parameter in string (RBsoft)
Split("Here is a test string to take apart", " ") - 'returns the string split into List elements at each occurance of the 2nd parameter (RBsoft)   
MB("My Text Here") - 'same as MsgBox() but only the one parameter is needed

*** Just Added These Three New Functions: August 25th, 2011 - 1.10pm

s.Proper() – Example: converts “jerry smith” to “Jerry Smith” or "ms. betty sue smith" to "Ms. Betty Sue Smith"
s.Lower()
s.Upper()

*** Just Added These Three New Functions: July 28th, 2011 - 12.27am

s.Space()
s.RndChrGen() - Generate random characters to fill Edit.Text, etc.
s.Exist()

*** Just Added These Two New Functions: July 24th, 2011 - 2.27am

s.Empty()
s.iif() - (Immediate If - very useful)
Example: MyVar = s.iif(File.ExternalWritable, File.DirRootExternal, File.DirInternal)

I have now been writing in B4A for just over three weeks. Each day I learn something new and how powerful it is! But, at first I was lost and did not know how flexable it is but was still missing some string functions I used all the time in VB and others like Visual Fox. I have put together a sample of some UDFs I wrote and wanted to share them as so many others here have done! I hope it is useful for someone. The new functions are listed below:

s.At()
s.Left()
s.Len()
s.Ltrim()
s.Mid()
s.Right()
s.Rtrim()
s.Stuff()
s.Trim()
s.Val()



Thanks,

Margret
 
Last edited:
Top