Question 1 Report
Data is stored as a comma-separated string: "Alice,85,A"
(a) Write pseudocode for a function GetField that takes a CSV string and a field number (1, 2 or 3) and returns that field as a string. For example, GetField("Alice,85,A", 2) should return "85". [5]
(a) The GetField function parses a comma-separated string by scanning for comma delimiters and tracking which field it is currently in. When it reaches the requested field number, it extracts and returns the substring from the start of that field to just before the next comma (or the end of the string for the last field). [5]
FUNCTION GetField(CSVString : STRING, FieldNum : INTEGER) RETURNS STRING
DECLARE CurrentField : INTEGER
DECLARE Start : INTEGER
DECLARE i : INTEGER
CurrentField ← 1
Start ← 1
FOR i ← 1 TO LENGTH(CSVString)
IF CSVString[i] = ',' THEN
IF CurrentField = FieldNum THEN
RETURN SUBSTRING(CSVString, Start, i - Start)
ENDIF
CurrentField ← CurrentField + 1
Start ← i + 1
ENDIF
NEXT i
IF CurrentField = FieldNum THEN
RETURN SUBSTRING(CSVString, Start, LENGTH(CSVString) - Start + 1)
ENDIF
RETURN ""
ENDFUNCTIONThe algorithm works as follows:
For the example GetField("Alice,85,A", 2): the loop finds the first comma at position 6. CurrentField is 1, not 2, so it increments CurrentField to 2 and sets Start to 7. It finds the second comma at position 9. CurrentField is now 2, which matches FieldNum, so it returns SUBSTRING("Alice,85,A", 7, 2) which is "85".
Everything you need to excel in your exams