3.2.8 - String operations and conversions (VB.NET)
Locate and extract text, join it, convert character codes and move between text and numeric values in VB.NET. Native code answers are written without Run; the optional Python demonstration explores a text transformation.
Length and character position
String length counts characters, while an index identifies one character's position.
Dim word As String = "ROBOT"
Console.WriteLine(word.Length)
Console.WriteLine(word(1))
Console.WriteLine(word.IndexOf("O"c))
The outputs are 5, O and 1. Native string indexing starts at 0: R is at 0, the two Os are at 1 and 3, and T is at 4. IndexOf returns the first matching position, not a count. word.IndexOf("Z"c) returns -1 because the character is absent. Check that result before using it as an index.
The last valid index is word.Length - 1; word(word.Length) is outside the string. An empty string has length 0 and no valid character index. A question's explicitly stated index convention takes precedence for supplied data; native methods still have their native semantics.
Substrings and concatenation
A substring extracts consecutive characters; concatenation joins strings into a new string.
Dim word As String = "ROBOT"
Dim middle As String = word.Substring(1, 3)
Dim label As String = "Item: " & middle
Console.WriteLine(label)
Substring(start,length) uses a zero-based start and a character count. Starting at 1 and taking 3 characters extracts OBO, so the output is Item: OBO. It does not replace the original word. word.Substring(2) takes everything from index 2 onward, BOT. Ensure start plus length does not exceed the original length.
AQA supplied SUBSTRING(1,3,word) uses an inclusive final index, also extracting OBO. For SUBSTRING(2,4,word), the AQA result is BOT; its VB.NET equivalent is word.Substring(2,3), taking three characters from index 2. Work out the required positions instead of blindly copying argument meanings. VB.NET's older Mid function uses one-based starting positions: Mid(word,2,3) also gives OBO.
The operator & joins text. "12" & "3" yields "123", not the number 15. Add numeric values only after converting numeric text appropriately.
Optional Python demonstration — a new string. Predict then run. Change the slice endpoint from 4 to 3 and run again. Python's endpoint is exclusive; this demonstration's word[1:4] corresponds to VB.NET Substring(1,3).
Optional Python demonstration: extract then join
{"exercise_id":"aqa8525-vbnet-string-demo","task_version":"1","runtime_profile":"python-console-v1","original_filename":"string_demo.py","file_mode":"fresh","code":"word = "ROBOT"\nmiddle = word[1:4]\nprint("Item: " + middle)\nprint(word)\n","instructions":"Predict and run. Change word[1:4] to word[1:3] and run again; explain the new extracted text and why the original word remains unchanged."}
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account