Working with Strings
There are two key Delphi functions that can be used in combination to do pretty much anything with strings. In the example below you are asked to read a text file on the Student Share K: Drive. The file is called 'CSVTemps.CSV'.
It was produced from Excel and is in Comma Separated Values format, where each item of data is separated by a comma. The task is to read the temperature value for each month and calculate the average for the year. To do this you'll need to read each line, find the position of the comma and read from the comma to the end of the line. |
The two useful Delphi functions:
pos(needle,haystack) |
The Pos function finds the position of one string needle within another, haystack.
It returns an integer, which is the first location found. If the string is not found, 0 is returned. The search IS case sensitive. var |
copy(sourcestring,start,end) |
The copy function returns a string which is a slice of the source string, starting at positon 'start' and ending at either position 'end' or the actual end of the string, whichever comes first.
var |
You can use these two functions in combination to progressively work through the string, finding characters and slicing the string. This is essential if you want to find the second or third match in a string. Pos will only return the first match, so the string must be cut up to find other matches.
Reading the CSV file
A CSV file might look a bit odd, but it's still a text file, just one with a particular structure.
Use the standard Delphi text file functions to open and read the file: Assign(file variable, full path of file) Reset(file variable) Readln(file variable, input string) Close(file variable) |
var |
Finding the position of the comma and slicing the string
Modify the while loop to search for the comma with 'pos' and use the resulting position to extract just that part of the input string.
|
begin |
Complete the program by making sure it skips the first result (which is the title), convert the result string to an integer, add them all up and average the result.