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,215
  • 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,539
  • StringFunctions 1.05.zip
    10.6 KB · Views: 8,510
Last edited:

ivavilagu

Member
Licensed User
Longtime User
Try this sample code. If it does not work, you will need to download an older version of string functions library as you are running an older version of B4A and that may be where the issue is.

B4X:
Sub Process_Globals
End Sub
Sub Globals
    Dim SF As StringFunctions
    SF.Initialize
End Sub
Sub Activity_Create(FirstTime As Boolean)
    Dim a As String
    a = SF.Encrypt("Test Message")
    SF.MB(a)
    a = SF.Decrypt(a)
    SF.MB(a)
    Activity.Finish
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub

You are right. I try with 1.04 and doesn´t work but with the 1.03 all work fine without errors.

Thanks!!!!!
 

thehe

Member
Licensed User
Longtime User
I have three images: a.png, b.png, c.png
In Sub Globals

Dim bitNameAr(3) As String
Private ImageView1 As ImageView
Private Button1 As Button

In Activity-Create:
bitNameAr(0) = "a.png"
bitNameAr(1) = "b"
bitNameAr(2) = ".png"

Sub Button1_Click
' ImageView1.Bitmap = LoadBitmap(File.DirAssets, bitNameAr(0)) ' Work with bitNameAr(0) = "a.png"
' ImageView1.Bitmap = LoadBitmap(File.DirAssets, bitNameAr(1) + ".png" )' do NOT work with bitNameAr(1) = "b"
ImageView1.Bitmap = LoadBitmap(File.DirAssets, "c" + bitNameAr(2) )' do NOT work with bitNameAr(2) = ".png"
End Sub
Would please help Between String Array and String
I expect I can ADD before or AFTER Array of String a,b, c to simplify declaration Array(0) + ".mp3" or Array(0) + ".png" . . . .
Van
 

Informatix

Expert
Licensed User
Longtime User
I have three images: a.png, b.png, c.png
In Sub Globals

Dim bitNameAr(3) As String
Private ImageView1 As ImageView
Private Button1 As Button

In Activity-Create:
bitNameAr(0) = "a.png"
bitNameAr(1) = "b"
bitNameAr(2) = ".png"

Sub Button1_Click
' ImageView1.Bitmap = LoadBitmap(File.DirAssets, bitNameAr(0)) ' Work with bitNameAr(0) = "a.png"
' ImageView1.Bitmap = LoadBitmap(File.DirAssets, bitNameAr(1) + ".png" )' do NOT work with bitNameAr(1) = "b"
ImageView1.Bitmap = LoadBitmap(File.DirAssets, "c" + bitNameAr(2) )' do NOT work with bitNameAr(2) = ".png"
End Sub
Would please help Between String Array and String
I expect I can ADD before or AFTER Array of String a,b, c to simplify declaration Array(0) + ".mp3" or Array(0) + ".png" . . . .
Van
The operator to concatenate strings is &, not +.
 

DaveW

Active Member
Licensed User
Longtime User
Hi Margret,
I tried the SplitGetWord() function but it only seems to return the first letter of the element, not the whole element.
i.e. ANS = SF.SplitGetWord("This|is|a|test|string.", "|", 2) returns "i" not "is".
 

Chr6373

New Member
Licensed User
Longtime User
Tutorial says:
InString
(YourString As String, SearchFor As String))
Returns the position of the SearchFor within YourString."


Like the SplitGetWord() function, note a result that can occur when using a quoted search using InString.
This is important to know when working with "CSV1","CSV2" types of data strings.


Example in B4A:
Dim strTest As String
strTest = "Test" & Chr("34") & "This"
Dim intTest As Int
intTest = sf.InString(strTest,"Th")
Msgbox("A test using the phrase: " & strTest & CRLF & "intTest = sf.instring(strTest," & Chr(34) & "Th" & Chr(34) & ") = " & "intTest=" & intTest,"Example")

MSGBOX RESULTS:

A test using the phrase: Test"This
intTest = sf.InString(strTest,"Th") = intTest=5

While B4A reports intTest=5, in Visual Basic this would be intTest=6







 

susu

Well-Known Member
Licensed User
Longtime User
Split seems not work with delimiter "|"

sf.Split("This is first|This is second|This is third", "|")

Result will be:
"T"
"h"
"i"
"s"
.....
 

shashkiranr

Active Member
Licensed User
Longtime User
Hi All,

Getting the below exception for MidExtract
B4X:
Bank:kjjhhg:Cardnumber/355478/cvv;39588;


java.lang.StringIndexOutOfBoundsException: length=0; regionStart=1; regionLength=-1


    at java.lang.String.startEndAndLength(String.java:588)
    at java.lang.String.substring(String.java:1475)
    at adr.stringfunctions.stringfunctions._vvvv6(stringfunctions.java:479)
    at com.bayalu.rahasya.encryption._decrypt_data(encryption.java:321)
    at com.bayalu.rahasya.encryption._encrypt_data(encryption.java:523)
    at com.bayalu.rahasya.adddata._savebutton_click(adddata.java:602)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:187)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:175)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:171)
    at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:77)
    at android.view.View.performClick(View.java:4654)
    at android.view.View$PerformClick.run(View.java:19438)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5602)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)

The following code is used

B4X:
fd = Bank:kjjhhg:Cardnumber/355478/cvv;39588

sf.Initialize
Dim res As String = sf.MidExtract(fd,":",":")

Regards,
SK
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I'm not familiar with this library implementation however you can use Regex:
B4X:
Dim s As String = "Bank:kjjhhg:Cardnumber/355478/cvv;39588"
Dim m As Matcher = Regex.Matcher(":([^:]+):", s) 'the pattern will look for a colon followed by any number of characters other than colon and then a color. The characters in the middle are grouped.
If m.Find Then
   Log(m.Group(1))
End If
 

Troberg

Well-Known Member
Licensed User
Longtime User
Suggestion:

Two string handling functions I've made which I use a a lot and find very handy are these:

'Count the number of values in a string, separated by Separator
CountValues(Text as string, Separator as string) as int
'Returns the value at ValueNumber Position, using Separator to count the values. Returns empty string if no value.
GetValueNumber(Text as string, Separator as string, ValueNumber as string) as string

I know this can be done by splitting the string into an array, but that's more awkward for a simple case. For example:

'Splitting a key-value string from a line read from a file
Key=GetValueNumber(Line, "=", 1)
Value=GetValueNumber(Line, "=", 2)

Neat and gives clear, readable code. I think these are the second most used methods I use, counted by how many project they are included in.
 

Troberg

Well-Known Member
Licensed User
Longtime User
Some other handy string functions I use a lot (all of these can be done with a few lines, but I find the code much more readable like this):

BeginsWith(Text as string, FindStr as string) as bool
'Returns true if Text begins with FindStr
EndsWith(Text as string, FindStr as string) as bool
'Returns true if Text ends with FindStr, very useful when checking file extensions
Contains(Text as string, FindStr as string) as bool
'Returns true if Text contains FindStr
CutFirst(Text as string, CutLen as int) as string
'Cuts the first CutLen characters from Text
CutLast(Text as string, CutLen as int) as string
'Cuts the last CutLen characters from Text
FilterText(Text as string, Allowed as string) as string
'Removes all characters from Text which are not in Allowed
GetBetween(Text as string, StartMarker as string, EndMarker as string, StartPos as int) as string
'Gets the content between StartMarker and EndMarker in Text, starting the search at StartPos. Useful for situations like getting the number from "Somefile (3).ext"

Some may think it's excessive to make simple 1-3 line subs like these, but they make for much more readable code. I've made a program to format e-books in txt format, and it makes heavy use of string handling, and these has made the code approximately 3800 times more readable.
 

DonManfred

Expert
Licensed User
Longtime User
Some of them alredy there (in the core!)
B4X:
    Dim test As String
    Log("Contains e:"&test.Contains("E"))
    Log("EndsWith a:"&test.EndsWith("a"))
    Log("StartWith T:"&test.StartsWith("T"))
just to name some... Did not look deeper
 

Troberg

Well-Known Member
Licensed User
Longtime User
Sorry, I'm not at my B4A computer, so I couldn't check, so I just went with what I remembered that I had written for my TextFormat program.
 

henrywood

Active Member
Licensed User
Longtime User
@margret: Could you be persuaded to upload the B4A code (.bas file) for StringFunctions 1.05, please ?

I would like to use it in my iOS / B4i app where your excellent library is sadly missing....

Thanks


/Henrik
 

Johan Schoeman

Expert
Licensed User
Longtime User
@margret: Could you be persuaded to upload the B4A code (.bas file) for StringFunctions 1.05, please ?

I would like to use it in my iOS / B4i app where your excellent library is sadly missing....

Thanks


/Henrik
I am not familiar with B4I but seeing that it supports inline Objective C code you could probably do something similar as to what I am trying to demonstrate in the attached B4A project with inline Java code. The Web is full of all kinds of methods that one can manipulate strings with (Java and C) for eg StackOverflow has plenty of examples. I guess B4I will also allow you to compile the newly created class to a library too. Thus, you should be able to add string manipulation methods to your liking and compile it to a library...

The B4A code in the class only takes care of the first four Java methods in the class. Add the additional B4A code in the class to call the other Java methods in the class. And then add to it as much as you want (and compile it to a library)
 

Attachments

  • MyStringUtilities.zip
    12.9 KB · Views: 219
Last edited:

appie21

Active Member
Licensed User
Longtime User
Hello

I have a string

a = "Hello how are you today"

How can i get tris strinfg to get start at 7 so that i get "how are you today"

I see the Mid but how do it works

i have install the library
 

imgsimonebiliato

Well-Known Member
Licensed User
Longtime User
Hello

I have a string

a = "Hello how are you today"

How can i get tris strinfg to get start at 7 so that i get "how are you today"

I see the Mid but how do it works

i have install the library

Use substring.
B4X:
Dim s as string
s = "Hello how are you today"
Log (s.SubString(6))
 

Johan Schoeman

Expert
Licensed User
Longtime User
Hello

I have a string

a = "Hello how are you today"

How can i get tris strinfg to get start at 7 so that i get "how are you today"

I see the Mid but how do it works

i have install the library
Mid works as follows:

Dim sf as StringFunctions
Dim a as String
a = "Hello how are you today"
sf.Initialize
a = sf.Mid(a, 7, 17) 'The string to use, the starting char number counting from 1, the number of characters to extract from and including the starting character.
Log(a)

You could also do:
a = sf.Mid(a, 7, sf.Len(a) - 6)

The above only to explain the Mid function of this library. Not sure I have all the CAPS correct - typing this on my IPad
 
Top