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

Asc

Integer

AscByte

Integer

BeginsWith

value As String, options As ComparisonOptions, locale As Locale

Boolean

Bytes

Integer

Characters

Iterable

ChrByte

value As Integer

String

Codepoints

Iterable

Compare

other As String, Optional compare As ComparisonOptions = ComparisonOptions, Optional locale As Locale = Nil

Integer

ConvertEncoding

newEncoding As TextEncoding

String

CountFields

separator As String

Integer

DefineEncoding

enc As TextEncoding

String

Encoding

TextEncoding

EndsWith

value As String, options As ComparisonOptions, locale As Locale

Boolean

FromArray

delimiter As String

String

IndexOf

startPosition As Integer, searchString As String, options As ComparisonOptions, locale As Locale

Integer

IndexOfBytes

startPosition As Integer, searchString As String

Integer

IsEmpty

Boolean

LastField

separator As String

Integer

Left

count As Integer

String

LeftBytes

count As Integer

String

Length

Integer

Lowercase

String

Middle

index As Integer, length As Integer

String

MiddleBytes

start As Integer, Optional length As Integer

String

NthField

separator As String, fieldNumber As Integer

String

Replace

oldString As String, newString As String

String

ReplaceAll

oldString As String, newString As String

String

ReplaceAllBytes

oldString As String, newString As String

String

ReplaceBytes

oldString As String, newString As String

String

ReplaceLineEndings

replacementLineEnding As String

String

Right

count As Integer

String

RightBytes

count As Integer

String

Split

delimiter As String

String

SplitBytes

delimiter As String

String

Titlecase

String

ToArray

delimiter As String

String

ToDouble

Double

ToInt64

Int64

ToInteger

Integer

Trim

Optional ParamArray characters() As String

String

TrimLeft

Optional ParamArray characters() As String

String

TrimRight

Optional ParamArray characters() As String

String

Uppercase

String

Val

Double

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, locale As Locale) 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.Characters

Characters As Iterable

Allows you to iterate through the characters in a String.

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.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 Iterable

Returns an iterator that returns 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 compare As ComparisonOptions = ComparisonOptions, 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 compare 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.

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.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 Split 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 New 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.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, locale As Locale) 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(sourceArray, [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.

SourceArray is the array whose elements will be used to create result returned.

The optional delimiter is used in separating the elements of sourceArray 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(startPosition As Integer, searchString As String, options As ComparisonOptions, locale As Locale) As Integer

Returns the position of the first occurrence of a String inside another String.

If the find String is not found within the source String, -1 is returned. If the find String is an empty String, then start is returned. That is, myString.IndexOf(“”) returns 0 and myString.IndexOf(3,””) returns 3.

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.

If you need to find the byte position of the find String within the source String, use a MemoryBlock instead.

This example uses the IndexOf function to locate a String within another 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(4, "is") // returns 5
first = source.IndexOf("tester") // returns -1
first = source.IndexOf(0, "IS", ComparisonOptions.CaseSensitive) // returns -1

String.IndexOfBytes

IndexOfBytes(startPosition As Integer, searchString 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.

Dim 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.Length = 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.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.

The Left function returns characters from the source String starting from the left side (as the name implies).

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.

If you need the number of bytes in the String rather than the number of characters, use the Bytes function.

Technically, Length returns the number of code points rather than the number of characters. For example, if two code points are presented visually as a single character, its length will be reported as “2”, not “1”.

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 As String

Returns the source String with all characters converted to lowercase.

Returns the value with all alphabetic characters in lowercase.

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(index As Integer, 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.

The Middle function works properly with international text.

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(oldString As String, newString As String) As String

Replaces the first occurrence of a String with another String.

Replaces the first occurrence of oldString in sourceString with newString. Replace is case-insensitive.

If newString is an empty String (“”), the Replace function deletes the first occurrence of the oldString in the sourceString.

If oldString 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(oldString As String, newString 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 newString. ReplaceAll is case-insensitive.

If replacementString is an empty String (“”), the ReplaceAll function deletes every occurrence of the oldString in the original String.

If oldString 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(oldString As String, newString As String) As String

Replaces all occurrences of a String with another String.

The ReplaceAllBytes function replaces all occurrences of oldString in sourceString with newString. ReplaceAllBytes is case-sensitive because it treats the source String as a series of raw bytes.

If newString is an empty String (“”), the ReplaceAllBytes function deletes every occurrence of the oldString in the sourceString.

If oldString 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(oldString As String, newString As String) As String

Replaces the first occurrence of a String with another String.

Replaces the first occurrence of oldString in sourceString with newString. ReplaceBytes is the byte version of Replace.

If newString is an empty String (“”), the ReplaceBytes function deletes the first occurrence of the oldString in the sourceString.

If oldString 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(replacementLineEnding 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)

String.Right

Right(count As Integer) As String

Returns the last n characters from the String specified.

The Right function returns characters from the source String starting from the right side (as the name implies).

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.

Dim 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 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 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

String.ToDouble

ToDouble As Double

Returns the numeric equivalent of the source String. This function is the same as the Val function but is international-savvy.

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.

See the Val function for more information.

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.

It does recognize prefixes &o (octal), &b (binary), and &h (hexadecimal). However, spaces are not allowed in front of the ampersand. That is, &hFF returns 0, but &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 0

source = "123 45"
result = source.ToInt64 // returns 123

source = "&hFFF"
result = source.ToInt64 // returns 4095

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.

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 = "Hello World"
Var result As String = source.Trim("","") // 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.

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.Trim("*") // 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.

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 As String

Returns the source String with all characters converted to uppercase.

Returns the String with all alphabetic characters in uppercase.

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.

Sample code

Var s As String
s = "Hello, World!"

Compatibility

All projects types on all supported operating systems.

See also

-, +, *, /, <, <=, =, >=, >, <> operators; &u literal; ConvertEncoding, IsNumeric, VarType functions; Var, Static statements; Encodings module; TextEncoding, TextInputStream classes; Boolean, CFStringRef, Color, CString, Currency, Double, Integer, PString, Variant, WString data types.