The String service provides a collection of methods for string processing. These methods can be used to:
The String service recognises the following line breaks:
Symbolic name | ASCII number |
---|---|
Line feed Vertical tab Carriage return Line feed + Carriage return File separator Group separator Record separator Next line Line separator Paragraph separator | 10 12 13 10 + 13 28 29 30 133 8232 8233 |
The String service recognises the following whitespaces:
Symbolic name | ASCII number |
---|---|
Space Horizontal tab Line feed Vertical tab Form feed Carriage return Next line No-break space Line separator Paragraph separator | 32 9 10 11 12 13 133 160 8232 8233 |
Below is a list of escape sequences that can be used in strings.
Escape Sequence | Symbolic name | ASCII number |
---|---|---|
\n \r \t | Line feed Carriage return Horizontal tab | 10 13 9 |
To have the escape sequence "\n" interpreted as an actual string, simply use "\\n" instead of "\" & Chr(10).
Characters defined in the Unicode Character Database as “Other” or “Separator” are considered as non-printable characters.
Control characters (ascii code <= 0x1F) are also considered as non-printable.
To add quotes in strings use \' (single quote) or \" (double quote). For example:
Before using the ScriptForge.String service the ScriptForge library needs to be loaded using:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
Loading the library will create the SF-String object that can be used to call the methods in the String service.
The following code snippets show the three ways to call methods from the String service (the Capitalise method is used as an example):
Dim s as String : s = "abc def"
s = SF-String.Capitalize(s) ' Abc Def
Dim s as String : s = "abc def"
Dim svc : svc = SF-String
s = svc.Capitalize(s) ' Abc Def
Dim s as String : s = "abc def"
Dim svc : svc = CreateScriptService("String")
s = svc.Capitalize(s) ' Abc Def
The code snippet below illustrates how to invoke methods from the String service in Python scripts. The IsIPv4 method is used as an example.
from scriptforge import CreateScriptService
svc = CreateScriptService("String")
ip-address = '192.168.0.14'
svc.IsIPv4(ip-address) # True
The SF-String object provides the following properties for Basic scripts:
Name | ReadOnly | Description |
---|---|---|
sfCR | Yes | Carriage return: Chr(13) |
sfCRLF | Yes | Carriage return + Linefeed: Chr(13) & Chr(10) |
sfLF | Yes | Linefeed: Chr(10) |
sfNEWLINE | Yes | Carriage return + Linefeed, which can be1) Chr(13) & Chr(10) or 2) Linefeed: Chr(10) depending on the operating system. |
sfTAB | Yes | Horizontal tabulation: Chr(9) |
You can use the properties above to identify or insert the corresponding characters inside strings. For example, the Linefeed can be replaced by SF-String.sfLF.
The first argument of most methods is the string to be considered. It is always passed by reference and left unchanged. Methods such as Capitalise, Escape, etc return a new string after their execution.
Because Python has comprehensive built-in string support, most of the methods in the String service are available for Basic scripts only. The methods available for Basic and Python are: HashStr, IsADate, IsEmail, IsFileName, IsIBAN, IsIPv4, IsLike, IsSheetName, IsUrl, SplitNotQuoted and Wrap.
Capitalises the first character from each word in the input string.
svc.Capitalize(inputstr: str): str
inputstr: The string to be capitalised.
Dim sName as String : sName = "john smith"
Dim sCapitalizedName as String
sCapitalizedName = SF-String.Capitalize(sName)
MsgBox sCapitalizedName 'John Smith
Counts the number of occurrences of a substring or a regular expression within a string.
svc.Count(inputstr: str, substring: str, [isregex: bool], [casesensitive: bool]): int
inputstr: The input string to be examined
substring: The substring or the regular expression to be used during search
isregex: Use True if the substring is a regular expression (Default = False)
casesensitive: The search can be case sensitive or not (Default = False).
'Counts the occurrences of the substring "or" inside the input string (returns 2)
MsgBox SF-String.Count("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "or", CaseSensitive := False)
'Counts the number of words with only lowercase letters (returns 7)
MsgBox SF-String.Count("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "\b[a-z]+\b", IsRegex := True, CaseSensitive := True)
To learn more about regular expressions, refer to the Python's documentation on Regular Expression Operations.
Returns True if a string ends with a specified substring.
The function returns False when either the string or the substring have a length = 0 or when the substring is longer than the string.
svc.EndsWith(inputstr: str, substring: str, [casesensitive: bool]): bool
inputstr: The string to be tested.
substring: The substring to be searched at the end of inputstr.
casesensitive: The search can be case sensitive or not (Default = False).
'Returns True because the method was called with the default CaseSensitive = False
MsgBox SF-String.EndsWith("abcdefg", "EFG")
'Returns False due to the CaseSensitive parameter
MsgBox SF-String.EndsWith("abcdefg", "EFG", CaseSensitive := True)
Converts linebreaks and tabs contained in the input string to their equivalent escaped sequence (\\, \n, \r, \t).
svc.Escape(inputstr: str): str
inputstr: The string to be converted.
'Returns the string "abc\n\tdef\\n"
MsgBox SF-String.Escape("abc" & Chr(10) & Chr(9) & "def\n")
Replaces Tab characters Chr(9) by space characters to replicate the behaviour of tab stops.
If a line break is found, a new line is started and the character counter is reset.
svc.ExpandTabs(inputstr: str, [tabsize: int]): str
inputstr: The string to be expanded
tabsize: This parameter is used to determine the Tab stops using the formula: TabSize + 1, 2 * TabSize + 1 , ... N * TabSize + 1 (Default = 8)
Dim myText as String
myText = "100" & SF-String.sfTAB & "200" & SF-String.sfTAB & "300" & SF-String.sfNEWLINE & -
"X" & SF-String.sfTAB & "Y" & SF-String.sfTAB & "Z"
MsgBox SF-String.ExpandTabs(myText)
'100 200 300
'X Y Z
Replaces all non-printable characters in the input string by a given character.
svc.FilterNotPrintable(inputstr: str, [replacedby: str]): str
inputstr: The string to be searched
replacedby: Zero, one or more characters that will replace all non-printable characters in inputstr (Default = "")
Dim LF : LF = Chr(10)
Dim myText as String
myText = "àén ΣlPµ" & LF & " Русский" & "\n"
MsgBox SF-String.FilterNotPrintable(myText)
' "àén ΣlPµ Русский\n"
Finds in a string a substring matching a given regular expression.
svc.FindRegex(inputstr: str, regex: str, [start: int], [casesensitive: bool], [forward: bool]): str
inputstr: The string to be searched
regex: The regular expression
start: The position in the string where the search will begin. This parameter is passed by reference, so after execution the value of start will point to the first character of the found substring. If no matching substring is found, start will be set to 0.
casesensitive: The search can be case sensitive or not (Default = False).
forward: Determines the direction of the search. If True, search moves forward. If False search moves backwards (Default = True)
At the first iteration, if forward = True, then start should be equal to 1, whereas if forward = False then start should be equal to Len(inputstr)
Dim lStart As Long : lStart = 1
Dim result as String
result = SF-String.FindRegex("abCcdefghHij", "C.*H", lStart, CaseSensitive := True)
MsgBox lStart & ": " & result
'3: CcdefghH
In the example above, the new value of lStart can be used to keep searching the same input string by setting the Start parameter to lStart + Len(result) at the next iteration.
Hash functions are used inside some cryptographic algorithms, in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more.
The HashStr method returns the result of a hash function applied on a given string and using a specified algorithm, as a string of lowercase hexadecimal digits.
The hash algorithms supported are: MD5, SHA1, SHA224, SHA256, SHA384 and SHA512.
svc.HashStr(inputstr: str, algorithm: str): str
inputstr: The string to hash. It is presumed to be encoded in UTF-8. The hashing algorithm will consider the string as a stream of bytes.
algorithm: One of the supported algorithms listed above, passed as a string.
MsgBox SF-String.HashStr("œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ‘åß∂ƒ©˙∆˚¬", "MD5")
' c740ccc2e201df4b2e2b4aa086f35d8a
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
a-string = "œ∑¡™£¢∞§¶•ªº–≠œ∑´®†¥¨ˆøπ‘åß∂ƒ©˙∆˚¬"
hash-value = svc.HashStr(a-string, "MD5")
bas.MsgBox(hash-value)
# c740ccc2e201df4b2e2b4aa086f35d8a
Encodes the input string into the HTML character codes, replacing special characters by their & counterparts.
For example, the character é would be replaced by é or an equivalent numerical HTML code.
svc.HtmlEncode(inputstr: str): str
inputstr: The string to encode.
MsgBox SF-String.HtmlEncode("")
' "<a href="https://a.b.com">From α to ω</a>"
Returns True if the input string is a valid date according to a specified date format.
svc.IsADate(inputstr: str, [dateformat: str]): bool
inputstr: The string to be checked. If empty, the method returns False
dateformat: The date format, as a string. It can be either "YYYY-MM-DD" (default), "DD-MM-YYYY" or "MM-DD-YYYY"
The dash (-) may be replaced by a dot (.), a slash (/) or a space.
If the format is invalid, the method returns False.
MsgBox SF-String.IsADate("2020-12-31", "YYYY-MM-DD") ' True
This method checks the format of the input string without performing any calendar-specific checks. Hence it does not test the input string for leap years or months with 30 or 31 days. For that, refer to the IsDate built-in function.
The example below shows the difference between the methods IsADate (ScriptForge) and the IsDate (built-in) function.
Dim myDate as String : myDate = "2020-02-30"
MsgBox SF-String.IsADate(myDate, "YYYY-MM-DD") 'True
MsgBox IsDate(myDate) ' False
svc = CreateScriptService("String")
s-date = "2020-12-31"
result = svc.IsADate(s-date) # True
Returns True if all characters in the string are alphabetic.
Alphabetic characters are those characters defined in the Unicode Character Database as Letter.
svc.IsAlpha(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsAlpha("àénΣlPµ") ' True
MsgBox SF-String.IsAlpha("myVar3") ' False
Returns True if all characters in the string are alphabetic, digits or "-" (underscore). The first character must not be a digit.
svc.IsAlphaNum(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsAlphaNum("-ABC-123456-abcàénΣlPµ") ' True
MsgBox SF-String.IsAlphaNum("123ABC") ' False
Returns True if all characters in the string are Ascii characters.
svc.IsAscii(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsAscii("a%?,25") ' True
MsgBox SF-String.IsAscii("abcàénΣlPµ") ' False
Returns True if all characters in the string are digits.
svc.IsDigit(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsDigit("123456") ' True
MsgBox SF-String.IsDigit("-12a") ' False
Returns True if the string is a valid email address.
svc.IsEmail(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsEmail("first.last@something.org") ' True
MsgBox SF-String.IsEmail("first.last@something.com.br") ' True
MsgBox SF-String.IsEmail("first.last@something.123") ' False
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
bas.MsgBox(svc.IsEmail("first.last@something.org")) # True
bas.MsgBox(svc.IsEmail("first.last@something.com.br")) # True
bas.MsgBox(svc.IsEmail("first.last@something.123")) # False
Returns True if the string is a valid filename in a given operating system.
svc.IsFileName(inputstr: str, [osname: str]): bool
inputstr: The string to be checked. If empty, the method returns False.
osname: The operating system name, as a string. It can be "WINDOWS", "LINUX", "MACOSX" or "SOLARIS".
The default value is the current operating system on which the script is running.
MsgBox SF-String.IsFileName("/home/user/Documents/a file name.odt", "LINUX") ' True
MsgBox SF-String.IsFileName("C:\home\a file name.odt", "LINUX") ' False
MsgBox SF-String.IsFileName("C:\home\a file name.odt", "WINDOWS") ' True
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
bas.MsgBox(svc.IsFileName("/home/user/Documents/a file name.odt", "LINUX")) # True
bas.MsgBox(svc.IsFileName(r"C:\home\a file name.odt", "LINUX")) # False
bas.MsgBox(svc.IsFileName(r"C:\home\a file name.odt", "WINDOWS")) # True
Returns True if all characters in the string are hexadecimal digits.
svc.IsHexDigit(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
The hexadecimal digits may be prefixed with "0x" or "&H".
MsgBox SF-String.IsHexDigit("&H00FF") ' True
MsgBox SF-String.IsHexDigit("08AAFF10") ' True
MsgBox SF-String.IsHexDigit("0x18LA22") ' False
Returns True if the string is a valid International Bank Account Number (IBAN). The comparison is not case-sensitive.
svc.IsIBAN(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
True if the string contains a valid IBAN number.
' Basic
MsgBox SF-String.IsIBAN("BR15 0000 0000 0000 1093 2840 814 P2") ' True
# Python
result = svc.IsIBAN("BR15 0000 0000 0000 1093 2840 814 P2") # True
Returns True if the string is a valid IP(v4) address.
svc.IsIPv4(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsIPv4("192.168.1.50") ' True
MsgBox SF-String.IsIPv4("192.168.50") ' False
MsgBox SF-String.IsIPv4("255.255.255.256") ' False
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
bas.MsgBox(svc.IsIPv4("192.168.1.50")) # True
bas.MsgBox(svc.IsIPv4("192.168.50")) # False
bas.MsgBox(svc.IsIPv4("255.255.255.256")) # False
Returns True if the whole input string matches a given pattern containing wildcards.
svc.IsLike(inputstr: str, pattern: str, [casesensitive: bool]): bool
inputstr: The string to be checked. If empty, the method returns False.
pattern: The pattern as a string. Wildcards are:
casesensitive: The search can be case sensitive or not (Default = False).
MsgBox SF-String.IsLike("aAbB", "?A*") ' True
MsgBox SF-String.IsLike("C:\a\b\c\f.odb", "?:*.*") ' True
MsgBox SF-String.IsLike("name:host", "?*@?*") ' False
MsgBox SF-String.IsLike("@host", "?*@?*") ' False
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
bas.MsgBox(svc.IsLike("aAbB", "?A*")) # True
bas.MsgBox(svc.IsLike(r"C:\a\b\c\f.odb", "?:*.*")) # True
bas.MsgBox(svc.IsLike("name:host", "?*@?*")) # False
bas.MsgBox(svc.IsLike("@host", "?*@?*")) # False
Returns True if all characters in the string are in lowercase. Non-alphabetic characters are ignored.
svc.IsLower(inputstr: str): bool
InputStr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsLower("abc'(-xy4z") ' True
MsgBox SF-String.IsLower("1234") ' True
MsgBox SF-String.IsLower("abcDefg") ' False
Returns True if all characters in the string are printable.
svc.IsPrintable(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsPrintable("àén ΣlPµ Русский") ' True
MsgBox SF-String.IsPrintable("First line." & Chr(10) & "Second Line.") ' False
Returns True if the whole input string matches a given regular expression.
svc.IsRegex(inputstr: str, regex: str, [casesensitive: bool]): bool
inputstr: The string to be checked. If empty, the method returns False.
regex: The regular expression. If empty, the method returns False.
casesensitive: The search can be case sensitive or not (Default = False).
MsgBox SF-String.IsRegex("aAbB", "[A-Za-z]+") ' True
MsgBox SF-String.IsRegex("John;100", "[A-Za-z]+;[0-9]+") ' True
MsgBox SF-String.IsRegex("John;100;150", "[A-Za-z]+;[0-9]+") ' False
Returns True if the input string is a valid Calc sheet name.
svc.IsSheetName(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsSheetName("1àbc + ""déf""") ' True
MsgBox SF-String.IsSheetName("[MySheet]") ' False
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
bas.MsgBox(svc.IsSheetName("1àbc + ""déf""")) # True
bas.MsgBox(svc.IsSheetName("[MySheet]")) # False
A sheet name must not contain the characters [ ] * ? : / \ or the character ' (apostrophe) as first or last character.
Returns True if the first character of every word is in uppercase and the other characters are in lowercase.
svc.IsTitle(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsTitle("This Is The Title Of My Book") ' True
MsgBox SF-String.IsTitle("This is the Title of my Book") ' False
MsgBox SF-String.IsTitle("Result Number 100") ' True
Returns True if all characters in the string are in uppercase. Non alphabetic characters are ignored.
svc.IsUpper(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsUpper("ABC'(-XYZ") ' True
MsgBox SF-String.IsUpper("A Title") ' False
Returns True if the string is a valid absolute URL (Uniform Resource Locator) address. Only the http, https and ftp protocols are supported.
svc.IsUrl(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsUrl("http://foo.bar/?q=Test%20URL-encoded%20stuff") ' True
MsgBox SF-String.IsUrl("www.somesite.org") ' False
svc = CreateScriptService("String")
bas = CreateScriptService("Basic")
bas.MsgBox(svc.IsUrl("http://foo.bar/?q=Test%20URL-encoded%20stuff")) # True
bas.MsgBox(svc.IsUrl("www.somesite.org")) # False
Returns True if all characters in the string are whitespaces
svc.IsWhitespace(inputstr: str): bool
inputstr: The string to be checked. If empty, the method returns False.
MsgBox SF-String.IsWhitespace(" ") ' True
MsgBox SF-String.IsWhitespace(" " & Chr(9) & Chr(10)) ' True
MsgBox SF-String.IsWhitespace("") ' False
Returns the input string centre-justified.
The leading and trailing white spaces are stripped and the remaining characters are completed left and right up to a specified total length with the character padding.
svc.JustifyCenter(inputstr: str, [length: int], [padding: str]): str
inputstr: The string to be centre-justified. If empty, the method returns an empty string.
length: The length of the resulting string (default = the length of the input string).
If the specified length is shorter than the centre-justified input string, then the returned string is truncated.
padding: The single character to be used as padding (default = the Ascii space " ").
MsgBox SF-String.JustifyCenter("Title", Length := 11) ' " Title "
MsgBox SF-String.JustifyCenter(" ABCDEF", Padding := "-") ' "--ABCDEF--"
MsgBox SF-String.JustifyCenter("A Long Title", Length := 5) ' "ong T"
Returns the input string left-justified.
The leading white spaces are stripped and the remaining characters are completed to the right up to a specified total length with the character padding.
svc.JustifyLeft(inputstr: str, [length: int], [padding: str]): str
inputstr: The string to be left-justified. If empty, the method returns an empty string.
length: The length of the resulting string (default = the length of the input string).
If the specified length is shorter than the left-justified input string, then the returned string is truncated.
padding: The single character to be used as padding (default = the Ascii space " ").
MsgBox SF-String.JustifyLeft("Title", Length := 10) ' "Title "
MsgBox SF-String.JustifyLeft(" ABCDEF", Padding := "-") ' "ABCDEF----"
MsgBox SF-String.JustifyLeft("A Long Title", Length := 5) ' "A Lon"
Returns the input string right-justified.
The leading white spaces are stripped and the remaining characters are completed to the left up to a specified total length with the character padding.
svc.JustifyRight(inputstr: str, [length: int], [padding: str]): str
inputstr: The string to be right-justified. If empty, the method returns an empty string.
length: The length of the resulting string (default = the length of the input string).
If the specified length is shorter than the right-justified input string, then the returned string is truncated.
padding: The single character to be used as padding (default = the Ascii space " ").
MsgBox SF-String.JustifyRight("Title", Length := 10) ' " Title"
MsgBox SF-String.JustifyRight(" ABCDEF ", Padding := "-") ' "----ABCDEF"
MsgBox SF-String.JustifyRight("A Long Title", Length := 5) ' "Title"
Returns the input string enclosed in single or double quotes. Existing quotes are left unchanged, including leading and/or trailing quotes.
svc.Quote(inputstr: str, [quotechar: str]): str
inputstr: The string to quote.
quotechar: Either the single (') or double (") quote (default).
MsgBox SF-String.Quote("Text Value")
' "Text Value"
MsgBox SF-String.Quote("Book Title: ""The Arabian Nights""", "'")
' 'Book Title: "The Arabian Nights"'
This method can be useful while preparing a string field to be stored in a csv-like file, which requires that text values be enclosed with single or double quotes.
Replaces all occurrences of the characters specified in the Before parameter by the corresponding characters specified in After.
If the length of Before is greater than the length of After, the residual characters in Before are replaced by the last character in After.
svc.ReplaceChar(inputstr: str, before: str, after: str): str
inputstr: The input string on which replacements will occur.
before: A string with the characters that will be searched in the input string for replacement.
after: A string with the new characters that will replace those defined in before.
' Replaces accented characters
MsgBox SF-String.ReplaceChar("Protégez votre vie privée", "àâãçèéêëîïôöûüýÿ", "aaaceeeeiioouuyy")
' "Protegez votre vie privee"
MsgBox SF-String.ReplaceChar("Protégez votre vie privée", "àâãçèéêëîïôöûüýÿ", "")
' "Protgez votre vie prive"
MsgBox SF-String.ReplaceChar("àâãçèéêëîïôöûüýÿ", "àâãçèéêëîïôöûüýÿ", "aaaceeeeiioouuyy")
' "aaaceeeeiioouuyy"
The SF-String service provides useful public constants for the Latin character sets, as shown in the example below:
MsgBox SF-String.ReplaceChar("Protégez votre vie privée", SF-String.CHARSWITHACCENT, SF-String.CHARSWITHOUTACCENT)
' "Protegez votre vie privee"
Replaces all occurrences of a given regular expression by a new string.
svc.ReplaceRegex(inputstr: str, regex: str, newstr: str, [casesensitive: bool]): str
inputstr: The input string on which replacements will occur.
regex: The regular expression.
newstr: The replacing string.
casesensitive: The search can be case sensitive or not (Default = False).
MsgBox SF-String.ReplaceRegex("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "[a-z]", "x", CaseSensitive := True)
' "Lxxxx xxxxx xxxxx xxx xxxx, xxxxxxxxxxx xxxxxxxxxx xxxx." (each lowercase letter is replaced by "x")
MsgBox SF-String.ReplaceRegex("Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "\b[a-z]+\b", "x", CaseSensitive := False)
' "x x x x x, x x x." (each word is replaced by "x")
Replaces in a string some or all occurrences of an array of strings by an array of new strings.
svc.ReplaceStr(inputstr: str, oldstr: str, newstr: str, [occurrences: int], [casesensitive: bool]): str
inputstr: The input string on which replacements will occur.
oldstr: A single string or an array of strings. Zero-length strings are ignored.
newstr: The replacing string or the array of replacing strings.
If oldstr is an array, each occurrence of any of the items in oldstr is replaced by newstr.
If oldstr and newstr are arrays, replacements occur one by one up to the UBound(newstr).
If oldstr has more entries than newstr, then the residual elements in oldstr are replaced by the last element in newstr.
occurrences: The maximum number of replacements. The default value is 0, meaning that all occurrences will be replaced.
When oldstr is an array, the occurrence parameter is computed separately for each item in the array.
casesensitive: The search can be case sensitive or not (Default = False).
MsgBox SF-String.ReplaceStr("100 xxx 200 yyy", Array("xxx", "yyy"), Array("(1)", "(2)"), CaseSensitive := False)
' "100 (1) 200 (2)"
MsgBox SF-String.ReplaceStr("abCcdefghHij", Array("c", "h"), Array("Y", "Z"), CaseSensitive := False)
' "abYYdefgZZij"
Returns a string with a readable representation of the argument, truncated at a given length. This is useful mainly for debugging or logging purposes.
If the anyvalue parameter is an object, it will be enclosed with square brackets "[" and "]".
In strings, tabs and line breaks are replaced by \t, \n or \r.
If the final length exceeds the maxlength parameter, the latter part of the string is replaced by " ... (N)" where N is the total length of the original string before truncation.
svc.Represent(anyvalue: any, [maxlength: int]): str
anyvalue: The input value to be represented. It can be any value, such as a string, an array, a Basic object, a UNO object, etc.
maxlength: The maximum length of the resulting string. The default value is 0, meaning there is no limit to the length of the resulting representation.
MsgBox SF-String.Represent("this is a usual string") ' "this is a usual string"
MsgBox SF-String.Represent("this is a usual string", 15) ' "this i ... (22)"
MsgBox SF-String.Represent("this is a" & Chr(10) & " 2-lines string") ' "this is a\n 2-lines string"
MsgBox SF-String.Represent(Empty) ' "[EMPTY]"
MsgBox SF-String.Represent(Null) ' "[NULL]"
MsgBox SF-String.Represent(Pi) ' "3.142"
MsgBox SF-String.Represent(CreateUnoService("com.sun.star.util.PathSettings")) ' "[com.sun.star.comp.framework.PathSettings]"
Note that the representation of data types such as Arrays and ScriptForge.Dictionary object instances include both the data type and their values:
' An example with a Basic built-in Array
MsgBox SF-String.Represent(Array(1, 2, "Text" & Chr(9) & "here"))
' "[ARRAY] (0:2) (1, 2, Text\there)"
' An example with a ScriptForge Array
Dim aValues as Variant
aValues = SF-Array.RangeInit(1, 5)
MsgBox SF-String.Represent(aValues)
' "[ARRAY] (0:4) (1.0, 2.0, 3.0, 4.0, 5.0)"
' An example with a ScriptForge Dictionary
Dim myDict As Variant : myDict = CreateScriptService("Dictionary")
myDict.Add("A", 1) : myDict.Add("B", 2)
MsgBox SF-String.Represent(myDict)
' "[Dictionary] ("A":1, "B":2)"
Returns the input string in reversed order.
This method is equivalent to the built-in StrReverse Basic function.
To use the StrReverse function, the statement Option VBASupport 1 must be present in the module.
svc.Reverse(inputstr: str): str
inputstr: The string to be reversed.
MsgBox SF-String.Reverse("abcdefghij") ' "jihgfedcba"
Returns a zero-based array of strings with the lines in the input string. Each item in the array is obtained by splitting the input string at newline characters.
svc.SplitLines(inputstr: str, [keepbreaks: int]): str[0..*]
inputstr: The string to be split.
keepbreaks: When True, line breaks are preserved in the output array (default = False).
Dim a as Variant
a = SF-String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3")
' a = Array("Line1", "Line2", "Line3")
a = SF-String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3" & Chr(10))
' a = Array("Line1", "Line2", "Line3", "")
a = SF-String.SplitLines("Line1" & Chr(10) & "Line2" & Chr(13) & "Line3" & Chr(10), KeepBreaks := True)
' a = Array("Line1\n", "Line2\r", "Line3\n", "")
Splits a string into an array of elements using a specified delimiter.
If a quoted substring contains a delimiter, it is ignored. This is useful when parsing CSV-like records that contain quoted strings.
svc.SplitNotQuoted(inputstr: str, [delimiter: str], [occurrences: int], [quotechar: str]): str[0..*]
inputstr: The string to be split.
delimiter: A string of one or more characters that will be used as delimiter. The default delimiter is the Ascii space " " character.
occurrences: The maximum number of substrings to return. The default value is 0, meaning that there is no limit to the number of returned strings.
quotechar: Either the single (') or double (") quote.
arr1 = SF-String.SplitNotQuoted("abc def ghi")
' arr1 = Array("abc", "def", "ghi")
arr2 = SF-String.SplitNotQuoted("abc,""def,ghi""", ",")
' arr2 = Array("abc", """def,ghi""")
arr3 = SF-String.SplitNotQuoted("abc,""def\"",ghi""", ",")
' arr3 = Array("abc", """def\"",ghi""")
arr4 = SF-String.SplitNotQuoted("abc,""def\"",ghi"""",", ",")
' arr4 = Array("abc", """def\"",ghi""", "")
svc = CreateScriptService("String")
arr1 = svc.SplitNotQuoted('abc def ghi')
# arr1 = ('abc', 'def', 'ghi')
arr2 = svc.SplitNotQuoted('abc,"def,ghi"', ",")
# arr2 = ('abc', '"def,ghi"')
arr3 = svc.SplitNotQuoted(r'abc,"def\",ghi"', ",")
# arr3 = ('abc', '"def\\",ghi"')
arr4 = svc.SplitNotQuoted(r'abc,"def\",ghi"",', ",")
# arr4 = ('abc', '"def\\",ghi""', '')
Beware of the differences between Basic and Python when representing strings. For example, in Basic two "" characters inside a string are interpreted as a single " character. In Python, strings enclosed with single quotes can contain " characters without having to double them.
Returns True if the first characters of a string are identical to a given substring.
This method returns False if either the input string or the substring have a length = 0 or when the substring is longer than the input string.
svc.StartsWith(inputstr: str, substring: str, [casesensitive: bool]): bool
inputstr: The string to be tested.
substring: The substring to be searched at the start of inputstr.
casesensitive: The search can be case sensitive or not (Default = False).
MsgBox SF-String.StartsWith("abcdefg", "ABC") 'True
MsgBox SF-String.StartsWith("abcdefg", "ABC", CaseSensitive := True) 'False
Returns the input string without its leading and trailing whitespaces.
svc.TrimExt(inputstr: str): str
inputstr: The string to trim.
MsgBox SF-String.TrimExt(" Some text. ") ' "Some text."
MsgBox SF-String.TrimExt(" ABCDEF" & Chr(9) & Chr(10) & Chr(13) & " ") ' "ABCDEF"
Converts any escaped sequence (\\, \n, \r, \t) in the input string to their corresponding Ascii character.
svc.Unescape(inputstr: str): str
inputstr: The string to be converted.
MsgBox SF-String.Unescape("abc\n\tdef\\n")
' "abc" & Chr(10) & Chr(9) & "def\n"
Removes the single or double quotes enclosing the input string.
This is useful when parsing CSV-like records that contain quoted strings.
svc.Unquote(inputstr: str, [quotechar: str]): str
inputstr: The string to unquote.
quotechar: Either the single (') or double (") quote (default).
Dim s as String
' s = "Some text" (without enclosing quotes)
s = SF-String.Unquote("""Some text""")
' The string below does not have enclosing quotes, so it remains unchanged
' s = "Some text" (unchanged)
s = SF-String.Unquote("Some text")
' Quotes inside the string are not removed
' s = "The ""true"" meaning" (unchanged)
s = SF-String.Unquote("The ""true"" meaning")
Converts the input string into an array of substrings so that each item in the array has at most a given number of characters.
In practice, this method returns a zero-based array of output lines, without newlines at the end, except for the pre-existing line-breaks.
Tabs are expanded using the same procedure performed by the ExpandTabs method.
Symbolic line breaks are replaced by their equivalent Ascii characters.
If the wrapped output has no content, the returned array is empty.
svc.Wrap(inputstr: str, [width: int], [tabsize: int]): str
inputstr: The string to wrap.
width: The maximum number of characters in each line (Default = 70).
tabsize: Before wrapping the text, the existing TAB Chr(9) characters are replaced with spaces. The argument tabsize defines the TAB stops at TabSize + 1, 2 * TabSize + 1 , ... N * TabSize + 1 (Default = 8).
a = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
b = SF-String.Wrap(a, 20)
' Array("Neque porro ", "quisquam est qui ", "dolorem ipsum quia ", "dolor sit amet, ", "consectetur, ", "adipisci velit...")
a = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..."
b = svc.Wrap(a, 20)
# ('Neque porro ', 'quisquam est qui ', 'dolorem ipsum quia ', 'dolor sit amet, ', 'consectetur, ', 'adipisci velit...')
All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "-" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.