DataType
String
Description
A String is an intrinsic data type. It is a series of numeric or alphabetic characters enclosed in quotes.
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
value As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil |
|||
value As Integer |
String |
✓ |
|
value As Integer |
String |
✓ |
|
other As String, Optional comparison As ComparisonOptions = ComparisonOptions.CaseInsensitive, Optional locale As Locale = Nil |
|||
searchString As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil |
|||
newEncoding As TextEncoding |
String |
||
separator As String |
|||
enc As TextEncoding |
String |
||
✓ |
|||
value As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil |
|||
fields() As String, delimiter As String = " " |
String |
✓ |
|
searchString As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil |
|||
startPosition As Integer, searchString As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil |
|||
start As Integer = 0, find As String |
|||
separator As String |
|||
count As Integer |
String |
||
count As Integer |
String |
||
String |
|||
String |
|||
String |
|||
separator As String, fieldNumber As Integer |
String |
||
substring As String, replacementString As String |
String |
||
substring As String, replacementString As String |
String |
||
substring As String, replacementString As String |
String |
||
substring As String, replacementString As String |
String |
||
replacement As String |
String |
||
count As Integer |
String |
||
count As Integer |
String |
||
delimiter As String = " " |
String() |
||
delimiter As String = " " |
String() |
||
String |
|||
delimiter As String = " " |
String() |
||
Optional ParamArray characters() As String |
String |
||
Optional ParamArray characters() As String |
String |
||
Optional ParamArray characters() As String |
String |
||
String |
|||
Method descriptions
String.Asc
Asc As Integer
Returns the integer code point for the first character in the String using the character's encoding.
The Asc function returns the code point for the first character in the passed String in the characters encoding. Characters 0 through 127 are the standard ASCII set, which are the same on practically every encoding.
If you need to get the ASCII code of the first byte of the String rather than the first character, use the AscByte function.
This example uses the Asc function to get the ASCII value of a character.
Var result As Integer
Var source As String = "A"
result = source.Asc ' returns 65
This example gets the code point for the "≥" symbol
Var source As String = "≥"
Var result As Integer
result = source.Asc
String.AscByte
AscByte As Integer
Returns the integer value for the first byte of a String.
This function returns the code for the first byte in the String passed. If you need to get the character code of the first character of the String rather than the first byte, use the String function instead.
You should use AscByte instead of Asc when the String represents binary data.
This code gets the value of the first byte of a String:
Var s1 As String = "a"
Var byte As Integer
byte = s1.AscByte ' returns 97
Var s2 As String = "A"
byte = s2.AscByte ' returns 65
String.BeginsWith
BeginsWith(value As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil) As Boolean
Returns True if the String begins with the value passed.
BeginsWith tells you whether or not the source String begins with the value passed based upon the comparison option (case-sensitive or case-insensitive) and locale specified.
This example uses the BeginsWith function determine if the source String begins with "Inc.":
Var s As String
s = "Xojo, Inc."
If s.BeginsWith("Xojo", ComparisonOptions.CaseSensitive, Locale.Current) Then
System.Beep
MessageBox("It begins with Xojo.")
End If
String.Bytes
Bytes As Integer
Returns the number of bytes in the specified String.
Bytes treats String as a series of bytes, rather than a series of characters. It should be used when String represents binary data. If you need to know the number of characters in String rather than the number of bytes, use the Length function.
This example uses the Bytes function to return the number of bytes in a String.
Var s As String
s = "Hello World"
n = s.Bytes ' returns 11
String.CDbl
CDbl(Extends str As String) As Double
Returns the str passed as a Double.
String.CharacterCount
CharacterCount As Integer
Returns the number of visually distinct characters in the String.
In most cases, this will be the same value that would be returned by Length. It will differ when the String contains characters (such as emojis and characters from some written language character sets) each of which is a visually distinct single character but may require more than one unit of storage per character.
String.Characters
Characters As String()
Returns the string in an array where each visually distinct character is a single element.
This example is a function that takes a String (source) then returns the number of asterisks in it:
Var count As Integer
For Each char As String In source.Characters
if char = "*" then count = count + 1
Next
Return count
String.Chr
Chr(value As Integer) As String
Returns the value passed as a String.
This method is shared.
String.ChrByte
ChrByte(value As Integer) As String
Returns a single byte String from the specified value.
This method is shared.
Tip
Use ChrByte instead of Chr when working with binary data.
String.Codepoints
Codepoints As Integer()
Returns an array of UInt32 values for each Unicode scalar value that comprises the String.
Look for Unicode 65:
Var myString As String = "Once Upon A Time"
For Each codePoint As UInt32 In myString.Codepoints
If codePoint = 65 Then
' It is "A"
End If
Next
String.Compare
Compare(other As String, Optional comparison As ComparisonOptions = ComparisonOptions.CaseInsensitive, Optional locale As Locale = Nil) As Integer
Compares a String value with another String value. A non-empty String is always greater than an empty String. By default, a case-insensitive comparison is done. Returns a negative integer if the value is less than other, 0 if the two values are equal, and a positive integer if the value is greater than other.
By default this performs a case-insensitive comparison. To do a case-sensitive comparison, supply the ComparisonOptions.CaseSensitive enum value to the comparison parameter.
By default comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale parameter can be used to specify an explicit locale to do comparisons in.
When the locale parameter is provided a more unicode-savvy lexical comparison is used at the expense of performance.
A RuntimeException will be raised when the specified options are invalid.
Compare two String values:
Var dog As String = "Dog"
Var cat As String = "Cat"
Var result As Integer
result = dog.Compare(cat)
' result > 0
String.Contains
Contains(searchString As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil) As Boolean
Returns True if the string contains the searchString considering the options and locale passed.
Determine if the source string contains the String "Frodo":
If article.Contains("Frodo") Then
lordOfTheRingsReference = True
End If
String.ConvertEncoding
ConvertEncoding(newEncoding As TextEncoding) As String
Provides a quick way to convert a String of known encoding to some other encoding, without having to create a TextConverter object.
When you need to write text to a file that will be opened by another app that expects a particular encoding, use ConvertEncoding to convert the text to that encoding before you call the Write method.
The String must already have an encoding in order to convert it to something else. Use DefineEncoding to set an encoding if it does not have one.
The following code use the Encodings module to convert the text in a TextField to the ANSI encoding:
Var result As String
result = TextField1.Text.ConvertEncoding(Encodings.WindowsANSI)
Here is an example that converts the text in a TextField to the MacRoman encoding.
Var f As FolderItem
Var fileStream As TextOutputStream
file = FolderItem.SaveFileDialog(FileTypes1.Text, "My Info.txt")
If f <> Nil Then
fileStream = TextOutputStream.Create(f)
fileStream.Write(nameField.Text.ConvertEncoding(Encodings.MacRoman))
fileStream.Close
End If
String.CountFields
CountFields(separator As String) As Integer
Returns the number of values (fields) in the String passed that are separated by the separator String passed. If the source String is binary data or you require case-sensitivity, use a MemoryBlock instead.
The CountFields function is useful for reading columns of data from a text file where the fields are separated with a specific character or characters.
If the separator is not found within stringVariable, CountFields returns 1. If stringVariable is null, CountFields returns zero.
Note
Using CountFields in a loop to extract fields from a String is inefficient. You should use ToArray and Arrays.LastIndex for this purpose.
The code below returns 5.
Var count As Integer
Var s As String
s = "Dan*Smith*11/22/69*5125554323*Male"
count = s.CountFields("*")
The following code returns three because it counts the null "field" after the (unnecessary) final field delimiter.
Var count As Integer
Var s As String
s = "Dan*Smith*"
count = s.CountFields("*")
This code in the Opening event handler populates a PopupMenu and sets the initial value to the current month:
Var s As String
Var i, last As Integer
Var d As DateTime = DateTime.Now
s = "January,February,March,April,May,June,July," _
+ "August,September,October,November,December"
last = s.CountFields(",")
For i = 1 To last
Me.AddRow(s.NthField(",", i))
Next
Me.SelectedRowIndex = d.Month - 1
String.DefineEncoding
DefineEncoding(enc As TextEncoding) As String
Returns a String with the same data as the given String, but with the encoding of the passed encoding.
This function is useful when you have a String whose encoding is known to you but not to your application. The encoding of all strings created in your application is UTF-8, so you don't have to use DefineEncoding on them.
Consult the values of Base entry for TextEncoding when creating the TextEncoding object using the GetTextEncoding function.
The following code takes 8 bytes from a MemoryBlock and sets the encoding to UTF16.
Var source As String = MyMemoryBlock.StringValue(0, 8)
TextField1.Text = source.DefineEncoding(Encodings.UTF16)
This code uses DefineEncoding when reading text from a TCPSocket.
TextField1.Text = TCPSocket1.ReadAll.DefineEncoding(Encodings.UTF8)
String.EndOfLine
EndOfLine As EndOfLine
Returns the end of line character of the current OS.
This is as shared method.
String.Encoding
Encoding As TextEncoding
Returns the text encoding of the passed String.
This method does not attempt to "guess" the encoding of a String. It only returns the encoding of a String as it is known. Strings have a UTF-8 encoding by default. If you load data of another encoding into a String (from a file, perhaps), you will need to specify the encoding using DefineEncoding.
If the String's encoding is unknown, Encoding returns Nil. Test whether the TextEncoding object is Nil or include an Exception block if there is a chance the String's encoding would not be known at runtime.
Var f As FolderItem
Var t As TextInputStream
Var source As String
Var enc As TextEncoding
f = FolderItem.ShowOpenFileDialog("text") ' file type defined via the FileType class
If f <> Nil Then
t = TextInputStream.Open(f)
source = t.ReadAll
t.Close
End If
Try
enc = source.Encoding ' This will be Encodings.UTF8
' If the file actually has text in a different encoding, then specify the
' encoding using DefineEncoding
source = source.DefineEncoding(Encodings.UTF16LE)
enc = source.Encoding ' This is now Encodings.UTF16LE
Catch error As NilObjectException
MessageBox(error.Message)
End Try
String.EndsWith
EndsWith(value As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil) As Boolean
Returns True if the String ends with the value passed.
EndsWith tells you whether or not the source String ends with the value passed based upon the comparison option (case-sensitive or case-insensitive) and locale specified.
This example uses the EndsWith function determine if the source String ends with "Inc.":
Var source As String
source = "Xojo, Inc."
If source.EndsWith("Inc.", ComparisonOptions.CaseSensitive, Locale.Current) Then
System.Beep
MessageBox("It ends with Inc.")
End If
String.FromArray
FromArray(fields() As String, delimiter As String = " ") As String
Assigns a value to a String variable by concatenating the elements of a one-dimensional String array.
This method is shared.
fields is the array whose elements will be used to create result returned.
The optional delimiter is used in separating the elements of fields when creating result. The default is one space.
FromArray takes a one-dimensional String array and concatenates the individual elements into a single String variable. You can pass an optional delimiter which will be inserted between the fields in the resulting String. If no delimiter is passed, a single space will be used as the delimiter.
The String.ToArray function performs the opposite function. It takes a String and creates an array by parsing the string into array elements using a specified delimiter.
This example concatenates a three-element array into the string "Anthony,Aardvark,Accountant":
Var names() As String = Array("Anthony", "Aardvark", "Accountant")
Var combinedNames As String
combinedNames = String.FromArray(names, ",") ' returns "Anthony,Aardvark,Accountant"
String.IndexOf
IndexOf(searchString As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil) As Integer
Returns the position of the first occurrence of a searchString inside the source String.
If the searchString is not found within the source String, -1 is returned.
IndexOf is case-insensitive by default, even with accented Roman characters and non-Roman alphabets. If you wish to make a case-sensitive search, use the optional ComparisonOptions parameter.
This example uses the IndexOf function to locate the searchString within the source String:
Var first As Integer
Var source As String = "This is a test"
first = source.IndexOf("t") ' returns 0
first = source.IndexOf("is") ' returns 2
first = source.IndexOf("tester") ' returns -1
first = source.IndexOf("IS", ComparisonOptions.CaseSensitive) 'Returns -1
Note
If you need to find the byte position of the searchString within the source String, use a MemoryBlock instead.
IndexOf(startPosition As Integer, searchString As String, options As ComparisonOptions = ComparisonOptions.CaseInsensitive, locale As Locale = Nil) As Integer
Returns the position of the first occurrence after startPosition of searchString inside the source String. If searchString is an empty String, then startPosition is returned.
This example uses the IndexOf function to locate searchString within the source String.
Var first As Integer
Var source As String = "This is a test"
first = source.IndexOf(4, "") 'Returns 4
first = source.IndexOf(4, "is") 'Returns 5
String.IndexOfBytes
IndexOfBytes(start As Integer = 0, find As String) As Integer
Returns the byte position of the first occurrence of a String inside another String. The first character is numbered 0.
If the find String is not found within the source String, -1 (zero) is returned. IndexOfBytes is essentially case-sensitive since it treats the String as a series of raw bytes. It should be used instead of IndexOf when the String represents binary data.
If you need to find the character position of the find String within the source String, use the IndexOf function.
This example uses the IndexOfBytes function to locate a String within another String.
Var s As String = "This is a test"
first = s.IndexOfBytes("test") ' returns 10
String.IsEmpty
IsEmpty As Boolean
Returns True if the String is empty.
This is equivalent to String.Bytes = 0.
Check if the user entered data in a TextField:
If TextField1.Text.IsEmpty Then
MessageBox("Please enter a value in the field.")
End If
String.IsNumeric
IsNumeric As Boolean
Returns True if the string is a valid number and False if it is not.
Strings greater than 127 characters always return False.
In this example, IsNumeric is being used to inform the user the value they entered into a TextField is not a number:
If TotalPayment.IsNumeric = False Then
MessageBox("Please enter numbers only.")
End If
String.LastField
LastField(separator As String) As String
Returns the last field from a String of data. The first field is numbered 1. If you need to parse binary data, use a MemoryBlock instead.
The LastField function returns the last field value from the source based upon the separator passed.
The separator may be a String of any length.
If separator does not exist in the String then the entire String is returned.
This example returns "Male"
Var s, field As String
s = "Dan*Smith*11/22/69*5125554323*Male"
field = s.LastField("*")
MessageBox(field)
This example demonstrates the use of a multiple character separator.
Var days As String = "Monday--Tuesday--Wednesday--Thursday--Friday--Saturday--Sunday"
Var theDay As String = days.LastField("--") ' sets theDay to "Sunday"
String.Left
Left(count As Integer) As String
Returns the first n characters in a source String.
In most cases, Left returns the number of visually distinct characters you request from the left side of the String. However, it may not when the String contains characters (such as emojis and characters from some written language character sets) each of which is a visually distinct single character but may require more than one unit of storage per character.
Note
If you need to read bytes rather than characters, use the MemoryBlock class.
This example returns the first five characters in a String.
Var source As String = "Hello World"
source = source.Left(5) ' returns "Hello"
String.LeftBytes
LeftBytes(count As Integer) As String
Returns the first count bytes of the String.
The LeftBytes function returns bytes from the source String starting from the left side (as the name implies). The encoding of the result is the same as the encoding of the source String.
If you need to read the actual characters rather than bytes, use the String function.
This example uses the LeftBytes function to return the first 5 bytes from a String.
Var s As String = "Hello World"
s = s.LeftBytes(5) ' returns "Hello"
String.Length
Length As Integer
Returns the number of characters in the specified String.
In most cases, Length returns a value that is 1 for 1 to the number of visually distinct characters in the string. It will differ when the String contains characters (such as emojis and characters from some written language character sets) each of which is a visually distinct single character but may require more than one unit of storage per character.
Note
If you need the number of bytes in the String rather than the number of characters, use the Bytes function.
This example uses the Length function to return the number of characters in a String.
Var s As String
s = "Hello World"
n = s.Length ' returns 11
String.Lowercase
Lowercase(locale As Locale = Nil) As String
Returns the source String with all characters converted to lowercase.
Returns the value with all alphabetic characters in lowercase.
The locale As Locale parameter is required for non-Roman languages.
The examples below convert the value passed to lowercase.
Var result As String
Var source As String = "tHe Quick fOX"
result = source.Lowercase ' returns "the quick fox"
source = "THE 5 LAZY DOGS"
result = source.Lowercase ' returns "the 5 lazy dogs"
String.Middle
Middle
Middle(index As Integer, Optional length As Integer) As String
Returns a portion of a String. The first character is numbered 0.
To determine the number of characters in a String, use the Length function.
In most cases, Middle returns the number of visually distinct characters you request from the index position of the String. However, it may not when the String contains characters (such as emojis and characters from some written language character sets) each of which is a visually distinct single character but may require more than one unit of storage per character.
These examples use the Middle function to return portions of a String.
Var result As String
Var source As String = "This is a test"
result = source.Middle(5) ' returns "is a test"
result = source.Middle(10, 4) ' returns "test"
This example converts the text String in TextField1 to hex and writes the result to TextField2:
TextField2.Text = ""
For i As Integer = 1 To TextField1.Text.Length
TextField2.Text = TextField2.Text + "&h" + Hex(TextField1.Text.Middle(i, 1).Asc)
Next
String.MiddleBytes
MiddleBytes(start As Integer, Optional length As Integer) As String
Returns a portion of a String. The first character is numbered 0.
MiddleBytes treats source as a series of bytes, rather than a series of characters. MiddleBytes should be used when source represents binary data. The encoding of the result is the same as the encoding of the source String.
If you need to extract characters rather than bytes, use the Middle function. To determine the number of bytes in a String, use the Bytes function.
These examples use the MiddleBytes function to return portions of a String.
Var s As String = "This is a test"
s = s.MiddleBytes(10, 4) ' returns "test"
String.NthField
NthField(separator As String, fieldNumber As Integer) As String
Returns a field from a String of data. The first field is numbered 1. If you need to parse binary data, use a MemoryBlock instead.
The NthField function returns the field value from the source that precedes the fieldNumber occurrence of the separator in the source.
The separator may be a String of any length.
If fieldNumber is out of bounds, an empty String is returned. NthField is not case-sensitive.
Note
Using NthField in a loop to extract fields from a String is inefficient. You should use ToArray for this purpose.
This example returns "Smith"
Var s, field As String
s = "Dan*Smith*11/22/69*5125554323*Male"
field = s.NthField("*", 2)
MessageBox(field)
This example demonstrates the use of a multiple character separator.
Var days As String = "Monday--Tuesday--Wednesday--Thursday--Friday--Saturday--Sunday"
Var theDay As String = days.NthField("--", 3) ' sets theDay to "Wednesday"
String.Replace
Replace(substring As String, replacementString As String) As String
Replaces the first occurrence of a String with another String.
Replaces the first occurrence of substring in sourceString with replacementString. Replace is case-insensitive.
If replacementString is an empty String (""), the Replace function deletes the first occurrence of the substring in the sourceString.
If substring is an empty String (""), the Replace function returns an unchanged copy of the sourceString.
Below are some examples that show the results of the Replace function:
Var result As String
Var source As String = "the quick fox"
result = source.Replace("fox", "rabbit") ' returns "The quick rabbit"
result = source.Replace("f", "b") ' returns "The quick box"
result = source.Replace("quick ", "") ' returns "The fox"
String.ReplaceAll
ReplaceAll(substring As String, replacementString As String) As String
Replaces all occurrences of a String with another String.
The ReplaceAll function replaces all occurrences of substring in the original String with replacementString. ReplaceAll is case-insensitive.
If replacementString is an empty String (""), the ReplaceAll function deletes every occurrence of the substring in the original String.
If substring is an empty String (""), the ReplaceAll function returns an unchanged copy of the original String.
Below are some examples that show the results of the ReplaceAll function
Var result As String
Var source As String = "xyxyxy"
result = source.ReplaceAll("x", "z") ' returns "zyzyzy"
source = "the quick fox"
result = source.ReplaceAll(" ", "") ' returns "Thequickfox"
source = "the quick fox"
result = source.ReplaceAll(" ", ", ") ' returns "the, quick, fox"
String.ReplaceAllBytes
ReplaceAllBytes(substring As String, replacementString As String) As String
Replaces all occurrences of a String with another String.
The ReplaceAllBytes function replaces all occurrences of substring in sourceString with newString. ReplaceAllBytes is case-sensitive because it treats the source String as a series of raw bytes.
If replacementString is an empty String (""), the ReplaceAllBytes function deletes every occurrence of the substring in the sourceString.
If substring is an empty String (""), the ReplaceAllBytes function returns an unchanged copy of the sourceString.
ReplaceAllBytes is case-sensitive; it treats sourceString as a series of raw bytes. It should be used instead of ReplaceAll when the String represents a series of bytes or when your application will run in a one-byte character set (such as the US system) and you want case-sensitivity.
Below are some examples that show the results of the ReplaceAll function
Var result As String
Var source As String = "xyxyxy"
result = source.ReplaceAllBytes("x", "z") ' returns "zyzyzy"
source = "The quick fox"
result = source.ReplaceAllBytes(" ", "") ' returns "Thequickfox"
source = "The Quick Fox"
result = source.ReplaceAllBytes(" ", ", ") ' returns "The, Quick, Fox"
String.ReplaceBytes
ReplaceBytes(substring As String, replacementString As String) As String
Replaces the first occurrence of a String with another String.
Replaces the first occurrence of substring in sourceString with replacementString. ReplaceBytes is the byte version of Replace.
If replacementString is an empty String (""), the ReplaceBytes function deletes the first occurrence of the substring in the sourceString.
If substring is an empty String (""), the ReplaceBytes function returns an unchanged copy of sourceString.
ReplaceBytes is case-sensitive; it treats sourceString as a series of raw bytes. It should be used instead of Replace when the String represents a series of bytes or when your application will run in a one-byte character set (such as the US system) and you want case-sensitivity.
Below are some examples that show the results of the ReplaceBytes function:
Var result As String
result = ReplaceBytes("The quick fox", "fox", "rabbit") ' returns "The quick rabbit"
result = ReplaceBytes("The quick fox", "f", "b") ' returns "The quick box"
result = ReplaceBytes("The quick fox", "quick ", "") ' returns "The fox"
Using the second syntax:
Var result, s As String
s = "The quick fox"
result = s.ReplaceBytes("fox", "rabbit") ' returns "The quick rabbit"
String.ReplaceLineEndings
ReplaceLineEndings(replacement As String) As String
Replaces the line endings in the passed String with the specified replacement.
ReplaceLineEndings does a global search-and-replace for the end of line characters in SourceString using the specified value (replacement) as the replacement String. The search automatically recognizes Windows, macOS, and Unix line endings. Use this function to make multiline (or multi-paragraph) text compatible across platforms. The easiest way to specify the replacement value is with the EndOfLine class.
This example replaces the line endings in the text in a TextField with Windows line endings.
Var s As String
s = TextField1.Text.ReplaceLineEndings(EndOfLine.Windows)
Note
Replacing Unicode new line characters is not supported.
String.Right
Right(count As Integer) As String
Returns the last n characters from the String specified.
In most cases, Right returns the number of visually distinct characters you request from the right side of the String. However, it may not when the String contains characters (such as emojis and characters from some written language character sets) each of which is a visually distinct single character but may require more than one unit of storage per character.
Note
If you need to read bytes rather than characters, use the MemoryBlock class.
This example uses the Right function to return the last 5 characters from a String:
Var result As String
Var source As String = "Hello World"
result = source.Right(5) ' returns "World"
String.RightBytes
RightBytes(count As Integer) As String
Returns the last count bytes from the String.
The RightBytes function returns bytes from the source String starting from the right side (as the name implies). The encoding of the result is the same as the encoding of the source String.
RightBytes treats source as a series of bytes rather than a series of characters. It should be used when the String represents binary data. If you need to read characters rather than bytes, use the String function.
This example uses the RightBytes function to return the last 5 bytes from a String.
Var s As String = "Hello World"
s = s.RightBytes(5) ' returns "World"
String.Split
Split
Split(delimiter As String = " ") As String()
Creates a one-dimensional array from the String.
Use the Split function to create a new String array from a list of elements (or fields) that are separated by a delimiter. If the optional parameter, delimiter, is not passed, a single space is assumed as the delimiter. If the delimiter is an empty String, the source String is split into characters.
Split works exactly the same as ToArray.
The section of code specifies the comma delimiter and the second uses the default delimiter. They place each field into an array element, producing a three-element array. The last code section parses the String into individual characters.
Var anArray() As String
Var s As String
s = "Adam,Aardvark,Accountant"
anArray = s.Split(",") ' produces 3-element array
anArray = s.Split("") ' produces array of individual characters
String.SplitBytes
SplitBytes(delimiter As String = " ") As String()
Creates a one-dimensional array from the String passed. This method is identical to Split, except that it treats the source as binary data.
This function is intended for use with binary data. It can be used with normal encoded String data, but may not work as expected with some Japanese multibyte encodings.
Var anArray() As String
Var s As String = "Adam,Aardvark,Accountant"
anArray = s.SplitBytes(",") ' produces 3-element array
anArray = s.SplitBytes("") ' produces array of individual characters, but should be avoided for some encodings such as Japanese
String.Titlecase
Titlecase(locale As Locale = Nil) As String
Returns the String passed to it with all alphabetic characters in Titlecase.
Converts all characters in a String to lowercase characters and then converts the first character of each word to uppercase. Numbers are not affected.
The locale As Locale parameter is required for non-Roman languages.
The example below converts the values passed to Titlecase
Var result As String
Var source As String = "tHe Quick fOX"
result = source.Titlecase ' returns "The Quick Fox"
source = "THE LAZY DOG"
result = source.Titlecase ' returns "The Lazy Dog"
String.ToArray
ToArray(delimiter As String = " ") As String()
Creates a one-dimensional array from the String.
Use the ToArray function to create a new String array from a list of elements (or fields) that are separated by a delimiter. If the optional parameter, delimiter, is not passed, a single space is assumed as the delimiter. If the delimiter is an empty String, an array of characters is created from the source String.
ToArray works exactly the same as Split.
The section of code specifies the comma delimiter and the second uses the default delimiter. They place each field into an array element, producing a three-element array. The last code section parses the String into individual characters.
Var anArray(-1) As String
Var s As String
s = "Adam,Aardvark,Accountant"
anArray = s.ToArray(",") ' produces 3-element array
anArray = s.ToArray("") ' produces array of individual characters
Note
If the delimiter does not exist in the source String, an array with a single element containing the source string is returned.
String.ToBoolean
ToBoolean As Boolean
Returns True if the String is 1
or True
or False if it is any other value.
String.ToDouble
ToDouble As Double
Returns the numeric equivalent of the source String using the User's system settings for hundreds and decimal separators.
ToDouble should be used for numeric values that will be visible to the user. For purely internal values, the Val function can be used as it does not support the user's system settings.
ToDouble returns zero if String contains no numbers, except in the special case where the String begins with the String “NAN”. In this case, it returns "NAN(021)".
Numbers are converted only if they are found at the beginning of the String. Any numbers that follow a non-numeric value are ignored.
So,
"1AA2" returns 1 "AA2" returns 0 "12AA54" returns 12
This code use the ToDouble function to return the numbers contained in a String.
Var source As String
Var result As Double
source = "12345"
result = source.ToDouble ' returns 12345
source = "54.05car45"
result = source.ToDouble ' returns 54.05
source = "123.45"
result = source.ToDouble ' returns 123.45
source = "123 45"
result = source.ToDouble ' returns 123
source = "123,456"
result = source.ToDouble ' returns 123456
source = "auto"
result = source.ToDouble ' returns 0
source = "&hFFF"
result = source.ToDouble ' returns 4095
source = "&b1111"
result = source.ToDouble ' returns 15
String.ToInt64
ToInt64 As Int64
Returns the numeric form of a String as an Int64.
The ToInt64 function stops reading the String at the first character it doesn't recognize as part of a number. All other characters are automatically stripped.
Prefixes including &o (octal), &b (binary), and &h (hexadecimal) are recognized. However, spaces are not allowed in front of the ampersand. For example, & hFF returns 0, while &hFF returns 255.
ToInt64 returns zero if string contains no numbers.
This code use the ToInt64 function to return the numbers contained in a String literal or a String variable:
Var result As Int64
Var source As String = "12345"
result = source.ToInt64 ' returns 12345
source = " 12345"
result = source.ToInt64 ' returns 12345
source = "123 45"
result = source.ToInt64 ' returns 123
source = "&hFFF"
result = source.ToInt64 ' returns 4095
source = "& hFFF"
result = source.ToInt64 ' returns 0
source = "&b1111"
result = source.ToInt64 ' returns 15
String.ToInteger
ToInteger As Integer
Returns the integer equivalent of the source String. This function is the same as the Val function but is international-savvy.
For localized number formatting, use the Integer.FromString function instead. Generally, you will use Val for converting internal data and use ToInteger for converting data for input and output of user data.
ToInteger returns zero if String contains no numbers, except in the special case where the String begins with the String “NAN”. In this case, it returns "NAN(021)".
Numbers are converted only if they are found at the beginning of the String. Any numbers that follow a non-numeric value are ignored.
So,
"1AA2" returns 1 "AA2" returns 0 "12AA54" returns 12
This code use the ToInteger function to return the numbers contained in a String.
Var source As String
Var result As Integer
source = "12345"
result = source.ToInteger ' returns 12345
source = "54.05car45"
result = source.ToInteger ' returns 54
source = "123.45"
result = source.ToInteger ' returns 123
source = "123 45"
result = source.ToInteger ' returns 123
source = "123,456"
result = source.ToInteger ' returns 123
source = "auto"
result = source.ToInteger ' returns 0
source = "&hFFF"
result = source.ToInteger ' returns 4095
source = "&b1111"
result = source.ToInteger ' returns 15
String.Trim
Trim(Optional ParamArray characters() As String) As String
Returns the String passed with either whitespaces or the characters passed removed from the beginning and ending of the String.
Unless specific characters are passed in, Trim trims whitespace characters as defined by unicode.
Important
The characters parameter is not currently supported for Android.
This example removes the whitespaces from either side of the String passed:
Var source as String = " Hello World "
Var result as String = source.Trim ' Returns "Hello World"
This example removes *, and % from the beginning and ending of the String passed:
Var source as String = "**Hello World%%"
Var result as String = source.Trim("*", "%") ' Returns "Hello World"
This example trims the div tags from an HTML String:
Var source As String = "<div>Hello World</div>"
Var result As String = source.Trim("<div>","</div>") ' Returns "Hello World"
String.TrimLeft
TrimLeft(Optional ParamArray characters() As String) As String
Returns the String passed with either whitespaces or the characters passed removed from the left side of the String.
Unless specific characters are passed in, TrimLeft trims whitespace characters as defined by unicode.
Important
The characters parameter is not currently supported for Android.
This example removes the whitespaces from the left side of the String passed:
Var source As String = " Hello World "
Var result As String
result = source.TrimLeft ' Returns "Hello World "
This example removes * from the left side of the String passed:
Var source as String = "*Hello World*"
Var result as String = source.TrimLeft("*") ' Returns "Hello World*"
String.TrimRight
TrimRight(Optional ParamArray characters() As String) As String
Returns the String passed with either whitespaces or the characters passed removed from the right side of the String.
Unless specific characters are passed in, TrimRight trims whitespace characters as defined by unicode.
Important
The characters parameter is not currently supported for Android.
This example removes the whitespaces from the right side of the String passed:
Var source As String = " Hello World "
Var result As String
result = source.TrimRight ' Returns " Hello World"
This example removes * from the right side of the String passed:
Var source as String = "*Hello World*"
Var result as String = source.TrimRight("*") ' Returns "*Hello World"
String.Uppercase
Uppercase(locale As Locale = Nil) As String
Returns the source String with all characters converted to uppercase.
Returns the String with all alphabetic characters in uppercase.
The locale As Locale parameter is required for non-Roman languages.
The example below converts the value passed to uppercase.
Var result As String
Var source As String = "tHe Quick fOX"
result = source.Uppercase ' returns "THE QUICK FOX"
source = "the 5 lazy dogs"
result = source.Uppercase ' returns "THE 5 LAZY DOGS"
String.Val
Val As Double
Returns the numeric form of a String, always using US/English notation. For any user-visible numbers, you should use ToDouble instead.
Val recognizes prefixes &o (octal), &b (binary), and &h (hexadecimal). However, spaces are not allowed in front of the ampersand. That is, " &hFF" returns 255, but "&h FF" returns 0.
For localized number formatting, use the ToDouble function instead. Generally, you will use Val for converting internal data and use ToDouble for converting data for input and output of user data.
It is important to note that Val does not take separator characters into consideration. For example:
Var d As Double
d = Val("10,000.95") ' The "," causes the string to stop being converted
returns 10. Use ToDouble for data that is from the user as it may contain such characters. ToDouble handles imbedded separators in the input String.
Val returns zero if the String contains no numbers, except in the special case where the String begins with the String "NAN". In this case, it returns "NAN(021)".
As Val converts the String to a double, large integer values in a String could exceed the maximum integer value that a double can hold. In these cases, use ToInt64 to convert longer integer strings to Int64 values.
Numbers are converted only if they are found at the beginning of the String. Any numbers that follow a non-numeric value are ignored.
So,
"1AA2" returns 1
"AA2" returns 0
"12AA54" returns 12
These examples use the Val function to return the numbers contained in a String.
Var n As Double
n = Val("12345") ' returns 12345
n = Val("54.25car45") ' returns 54.25
n = Val("123.25") ' returns 123.25
n = Val("123 25") ' returns 123
n = Val("123,456") ' returns 123
n = Val("auto") ' returns 0
n = Val("&hFFF") ' returns 4095
n = Val("&b1111") ' returns 15
Var s As String
s = "12345"
n = s.Val ' returns 12345
Notes
Any kind of alphabetic or numeric information can be stored as a String. "Jean Marie", "3/17/98", "45.90" are all examples of strings. When you place quotes around information in your code, you are indicating the data as just a series of characters and nothing more. The maximum length of a String is limited only by available memory. The default value of a String is "".
All computers use encoding schemes to store character strings as a series of bytes. The oldest and most familiar encoding scheme is the ASCII encoding. It defines character codes only for values 0-127. These values include only the upper and lowercase English alphabet, numbers, some symbols, and invisible control codes used in early computers.
Many extensions to ASCII have been introduced which handle additional symbols, accented characters, non-Roman alphabets, and so forth. In particular, the Unicode encoding is designed to handle any language and a mixture of languages in the same String. Two different Unicode formats are supported: UTF-8 and UTF-16. Your constants, String literals, and so forth are nearly always stored internally using UTF-8 encoding.
If the strings you work with are created, saved, and read within your code, you shouldn't have to worry about encoding issues because the encoding is stored along with the content of the String.
Since character codes above 127 represent different characters in different encoding schemes, it is important that you understand the encoding that is used for strings that were generated outside of your app. When you read in a text String using the TextInputStream class, set the Encoding property to the correct encoding or use the optional Encoding parameter of the Read, ReadLine, or ReadAll methods. You can determine the encoding of a String using the Encoding function. If you need to save String data in a particular encoding, use the ConvertEncoding function. Specify the desired encoding using the Encodings module.
If you need to get a character that corresponds to the value of a character code, use the Chr function only if it is an ASCII code. In other cases, it is best to use the Chr method of the TextEncoding class. This enables you to specify both the encoding scheme and the desired character code.
The VarType function returns 8 when passed a String.
Iterating through characters
If you need to access each character of a String but don't need to know the index of that character, you can use an iterator:
Var wizard As String = "Gandalf"
For Each letter As String In wizard.Characters
MessageBox(letter)
Next
Converting from the text type
Text values automatically convert to String (with UTF8 encoding) when assigned:
Var t As Text = "Hello, World!"
Var s As String = t
Empty does not equal nil
Despite an empty String contains nothing, such String is not equivalent to Nil. Nil represents a non-existing object, whereas an empty String is an existing object even if it is empty.
Including double quotes
If you need to include a double quote mark inside your String literal, you can do it by typing two consecutive double quote marks. For example, a sentence like He told me "yes" can be typed in as a String literal as:
Var s As String = "He told me ""yes"""
Following the same logic, the literal """" actually represents a single double quote character (the first and last double quotes denote a String literal and the 2 consecutive double quotes in-between represents a double quote character).
The ampersand (&) character
Be aware that a single ampersand (&) character will often be interpreted as a keyboard shortcut if you are using your String literal inside the user interface, e.g. if you use your String literal as a button caption, a menu item… This behavior is aimed at implementing keyboard shortcuts (a.k.a. keyboard accelerators) on Microsoft Windows operating system. As a consequence, you may need to use "&&" instead of a single "&" character in some cases.
Escaping a character using the backslash (\) character
If a String is prefixed with the \ character, it will be treated as a C string literal and thus all standard string literal rules will apply.
Sample code
Var s As String
s = "Hello, World!"
Compatibility
All project types on all supported operating systems.