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,423
  • StringFunctions 1.01.zip
    7.3 KB · Views: 2,099
  • StringFunctions 1.03.zip
    7.4 KB · Views: 1,380
  • StringFunctions 1.04.zip
    7.6 KB · Views: 2,687
  • StringFunctions 1.05.zip
    10.6 KB · Views: 8,780
Last edited:

PierreK

New Member
Hello,

if I want to debug the app I got this error :(
Can anyone help me please. I can't find anything about this issue in google or the forum...

B4X:
*** Remote compilation mode ***
B4A version: 5.02 (1)
Parsing code.    (0.01s)
Compiling code.    (0.09s)
Compiling layouts code.    (0.02s)
Compiling debugger engine code.    (1.36s)
Sending data to remote compiler.    Error
step: Compiling generated Java code.
javac 1.7.0_09
src\b4a\example\main.java:343: error: package adr.stringfunctions does not exist
public adr.stringfunctions.stringfunctions _sf = null;
                          ^
Note: src\b4a\example\httputils2service.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

Thanks
Pierre
 

Arun

Member
Licensed User
Longtime User
I have developed and tested an app in the last few days and it was ready for demonstrating to a potential customer.

I had an issue with the progress bar yesterday, for which a new thread was created. In the meantime, I wanted to insert some more features.

Now, suddenly this message is appearing and I cant work any further on this app.

B4X:
*** Remote compilation mode ***
B4A version: 5.02 (1)
Parsing code.    (0.03s)
Compiling code.    (0.17s)
Compiling layouts code.    (0.00s)
Compiling debugger engine code.    (1.01s)
Sending data to remote compiler.    Error
step: Compiling generated Java code.
javac 1.7.0
src\b4a\example\main.java:348: error: package adr.stringfunctions does not exist
public adr.stringfunctions.stringfunctions _strfunc = null;
                          ^
1 error

Does it mean I cannot use the stringfunctions library in the Trial version?

Please let me know asap, as I will have to start my app from scratch.

Thanks
 

DonManfred

Expert
Licensed User
Longtime User
Does it mean I cannot use the stringfunctions library in the Trial version?
Yes. With the Trial you cannot use additional Libraries. You need a fullversion for this.
 

Arun

Member
Licensed User
Longtime User
I have downloaded the Trial version on 17th July and have spent the last 5 days working on this app (including the weekend)

The app was successfully tested using remote compilation to devices belonging to other members of my team. Not ONCE did this error come up, till now.

Isn't there any indication of what libraries can/cant be used in the Trial version? The Trial Version of B4A 2.0 which i had used 3 years ago was very specific about which libraries could and couldn't be used. I had then purchased the full version for 2 years.

Anyways, I am now wondering whether to pursue developing this app further. I wish this error had come in the beginning itself, then i would have known what restrictions I was working with.

Once again, thanks for the prompt reply.
 

Prosg

Active Member
Licensed User
Longtime User
hello
Maybe i find a bug with mid function:

B4X:
Dim str as string = "0900-1800"

Dim result as string = sf.mid(str, 5,2)
log (result)

'Bug : result return -1
 

vbmundo

Well-Known Member
Licensed User
Hi,

I have problems with your SPLIT function

Look

B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
   
    Dim TextoEncriptado As String, Texto As String, valores As List 
   
    SF.Initialize
   
    Telefono.SetScreenOrientation(1)
    Activity.LoadLayout("Principal")
    Activity.Title="Super MySQL"
    If File.Exists(Carpeta,"reg5.smql")=True Then
       TextoEncriptado=File.ReadString(Carpeta,Archivo)
       Texto=Decrypt(TextoEncriptado)
       valores=SplitMe(Texto,"|")
       txtServidor.Text=valores.Get(0)
       txtPort.Text=valores.Get(1)
       txtUser.Text=valores.Get(2)
       txtPassword.Text=valores.Get(3)
    End If
End Sub

Sub SplitMe(S As String,Delimiter As String) As List
Dim SF As StringFunctions
SF.Initialize
Return SF.Split(S,Delimiter)
End Sub

I have (for example.) this TEXT

"VALUE 1|XXXXXXX|YYYYYYYYY|GGGGGG"

And the Split function doesn'tretunt a WORD, only return the first Character.

What's Wrong ?

Regards
 

LucaMs

Expert
Licensed User
Longtime User
Hi,

I have (for example.) this TEXT

"VALUE 1|XXXXXXX|YYYYYYYYY|GGGGGG"

And the Split function doesn'tretunt a WORD, only return the first Character.

What's Wrong ?

Regards

The character "|" (Pipe) is a special character, then you should add a Backslash before it:
B4X:
Dim lstWords As List
lstWords = SplitMe("VALUE 1|XXXXXXX|YYYYYYYYY|GGGGGG", "\|")

For i = 0 to lstWords.Size - 1
    Log(i & Tab & lstWords.Get(i))
Next


Sub SplitMe(S As String, Delimiter As String) As List
    Dim SF As StringFunctions
    SF.Initialize
    Return SF.Split(S, Delimiter)
End Sub
 

LA3QMA

Member
Licensed User
Longtime User
I need some help with the mid() function.

B4X:
tekst = "111110000101001001101000001010"
Log(tekst.Length)

For x = 1 To tekst.Length Step 8
   Log(sf.Mid(tekst, x, 8))
Next

I'm getting a result like:
11111000
01010010
01101000

But i'm expecting:
11111000
01010010
01101000
001010

How can i easily fix this?
 

LA3QMA

Member
Licensed User
Longtime User
DonManfred: yes i tried starting at 0 but this is not working. And yes several languages are not consistent on whats starting with 0 or 1 so i have tried both.
 

klaus

Expert
Licensed User
Longtime User
It seems that the Mid functionality is not the same as in VB.
In VB if the rest of the string is smaller than the given length Mid returns the rest.
The Mid function in the B4A StringFunction library doesn't.
The StringFunction library was at the beginning a code module.
There were several versions. I have one of those old ones, but not a recent one, and at this time the function was this:
B4X:
Sub Mid(Text As String, Start As Int, Length As Int) As String
    Return Text.SubString2(Start - 1, Start + Length - 1)
End Sub
This shows that the rest will not be returned.
The code module was later compiled to a library and no source code anymore.

You could change your code to this one:
B4X:
Dim tekst = "111110000101001001101000001010" As String
Log(tekst.Length)

For x = 1 To tekst.Length Step 8
    If tekst.Length - x + 1 < 8 Then
        Log(sf.Mid(tekst, x, tekst.Length - x + 1))
    Else
        Log(sf.Mid(tekst, x, 8))
    End If
Next
Or to this using the B4A native function:
B4X:
For x = 0 To tekst.Length - 1 Step 8
    If tekst.Length - x < 8 Then
        Log(tekst.SubString2(x, tekst.Length))
    Else
        Log(tekst.SubString2(x, x + 8))
    End If
Next

Or this shorter one.
B4X:
For x = 0 To tekst.Length - 1 Step 8
    Log(tekst.SubString2(x, Min(x + 8, tekst.Length)))
Next
 

Johan Schoeman

Expert
Licensed User
Longtime User
hello Margret, you can upload the source code creating libraries please. thank you very much.
You can very easily do this with inline Java code - see the attached project and specifically the class StringUtilities
 

Attachments

  • VariousUtilities.zip
    215.5 KB · Views: 286

mototest

New Member
Licensed User
Longtime User
Hi
I have problem with example
B4X:
Dim text, pattern As String
text = "any text*any text*any text*"
pattern = "*" 'one or more digits
Dim Matcher1 As Matcher
Matcher1 = Regex.Matcher(pattern, text)
Do While Matcher1.Find
  Log("Found: " & Matcher1.Match)
Loop

When pattern is any character then works ok, but when I search "*" then compiler give below error, why ?

java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1:

Generally I want find all position "*" in string and extract text between two stars : *text*

Thanks
Boguslaw
 
Last edited:
Top