3.2.8 - String operations and conversions (C#)
Find and extract characters, join text, and convert between characters, codes and numbers. Native C# written answers have no Run. C# execution is unavailable here; the runnable activity is an optional Python demonstration.
Length and character position
A string is ordered text, so its length and each character's position help a program inspect that text.
For the ordinary characters used here, word.Length gives the character count. Indexes start at 0 and end at Length minus 1.
string word = "PLANET";
int length = word.Length;
char first = word[0];
int position = word.IndexOf('N');
The length is 6, the first character is 'P' and the position of N is 3. IndexOf finds the first matching occurrence and returns -1 when the character is absent. Position is an index, not the number of characters: word[6] is outside this string. word[word.Length - 1] selects the final T.
When comparing an indexed character, compare with a character literal, such as word[0] == 'P'. Character '1' represents a written digit; it is different from integer 1. AQA supplied pseudocode uses LEN and POSITION; native C# uses the forms shown here.
Substrings and concatenation
A substring extracts a consecutive section of text, while concatenation joins text to form a new string.
string word = "PLANET";
string middle = word.Substring(1, 3);
string label = "Code: " + middle;
C# Substring(start, length) begins at index 1 and takes three characters: L, A and N. The result is LAN, and the label is Code: LAN. Its second number is a length. AQA SUBSTRING(1, 3, word) instead specifies an inclusive end index and happens to give the same LAN in this example. In general these numbers differ: AQA indexes 2 through 4 require C# Substring(2, 3), giving ANE.
Extracting a substring does not change the original string. Store the returned value when it is needed later. Joining "A" + "B" gives "AB"; joining "3" + "4" gives "34", not numeric 7.
Predict the optional Python demonstration, then run it. Change the slice word[1:4] to word[2:5] and rerun. Python excludes its slice's end index; this is an optional demonstration, not native C# syntax.
Optional Python demonstration: extracting a code
{"code":"word = "PLANET"\ncode = word[1:4]\nprint(code)\nprint("Code: " + code)","instructions":"Predict and run. Change word[1:4] to word[2:5], predict the extracted text, then run again."}
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account