4.1.1.7 - Strings, character codes and dates (VB.NET)
Learn to locate and extract text, convert between characters and their codes, and convert numeric and date values without confusing stored data with its display. VB.NET work is written only; this route is incomplete: runnable support pending.
String length, positions and substrings
A string is an ordered sequence of characters; its position convention determines how you access and extract them. VB.NET's .NET string methods use zero-based positions. In the examples here, each displayed character occupies one position; more complex Unicode text can contain characters represented by multiple UTF-16 code units.
Dim label As String = "AA-042"
Dim length As Integer = label.Length
Dim separator As Integer = label.IndexOf("-"c)
Dim prefix As String = label.Substring(0, separator)
Dim digits As String = label.Substring(separator + 1)
Dim first As Char = label(0)
Dim message As String = prefix & ":" & digits
length is 6, separator is 2, prefix is "AA", digits is "042", first is "A"c and message is "AA:042". Substring(start, length) extracts a stated number of positions; Substring(start) extracts everything from that start to the end. Do not confuse the requested length with an ending index. Substring(3, 2) returns "04".
IndexOf returns the first matching position, or -1 if no match exists. Check the result before using it as an index when a separator is not guaranteed. Use StringComparison.Ordinal when you want an exact culture-independent string search, for example label.IndexOf("AA", StringComparison.Ordinal). With the Char search above, we are locating the literal hyphen.
Concatenation joins strings. Prefer & for this in VB.NET, making the text operation explicit. "12" & "3" produces "123", not numeric 15. Strings are immutable: assigning a concatenation or substring result does not edit an existing string in place. Valid indices for a nonempty string of length n are 0 through n−1; an empty string has no valid character index. Extracting beyond the end is an error.
Characters and their codes
A character code is a numeric representation of a character; it is not the same as interpreting that character as a numeric digit. In VB.NET, AscW converts a character to its UTF-16 code-unit value and ChrW converts a suitable code-unit value back to a character. For the basic Latin examples used here, the familiar Unicode and ASCII values agree.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account