Author: Jonas Bilinkevicius
How would I go about parsing TAB delimited text files? I'm having difficulty with
the chr(9) character.
Answer:
Solve 1:
1 { ... }
2 var
3 t: Textfile;
4 line: string;
5 elements: TStringlist;
6 begin
7 Assignfile(t, filename);
8 Reset(t);
9 try
10 elements := TStringlist.Create;
11 try
12 while not Eof(t) do
13 begin
14 ReadLn(t, line);
15 {The following ignores empty lines}
16 if IScan(#9, line, 1) > 0 then
17 begin
18 elements.clear;
19 SplitString(line, #9, elements);
20 ProcessElements(elements); {you write this}
21 end;
22 end;
23 finally
24 elements.Free
25 end;
26 finally
27 Closefile(t);
28 end;
29
30 {Return the position of the first instance of ch in S after position fromPos, or 0
31 if ch was not found}
32
33 function IScan(ch: Char; const S: string; fromPos: Integer): Integer;
34 var
35 i: Integer;
36 begin
37 Result := 0;
38 for i := fromPos to Length(S) do
39 begin
40 if S[i] = ch then
41 begin
42 Result := i;
43 Break;
44 end;
45 end;
46 end;
47
48 {Split the passed string into substrings at the position of the separator character
49 and add the substrings to the passed list. The list is not cleared first!}
50
51 procedure SplitString(const S: string; separator: Char; substrings: TStrings);
52 var
53 i, n: Integer;
54 begin
55 if Assigned(substrings) and (Length(S) > 0) then
56 begin
57 i := 1;
58 repeat
59 n := IScan(separator, S, i);
60 if n = 0 then
61 n := Length(S) + 1;
62 substrings.Add(Copy(S, i, n - i));
63 i := n + 1;
64 until
65 i > Length(S);
66 end;
67 end;
Solve 2:
68
69 procedure DelimitedListToStringList(const S: AnsiString; Delimiter: Char;
70 List: TStrings; NullValue: AnsiString);
71 var
72 iPos: Integer;
73 Temp, Temp1: AnsiString;
74 begin
75 if not Assigned(List) then
76 Exit;
77 List.Clear;
78 Temp := S;
79 iPos := Pos(Delimiter, S);
80 while iPos > 0 do
81 begin
82 SetLength(Temp1, iPos - 1);
83 Temp1 := Copy(Temp, 1, iPos - 1);
84 if Temp1 = '' then
85 begin
86 SetLength(Temp1, Length(NullValue));
87 Temp1 := NullValue;
88 end;
89 List.Add(Temp1);
90 Delete(Temp, 1, iPos);
91 iPos := Pos(Delimiter, Temp);
92 end;
93 if Temp > '' then
94 List.Add(Temp);
95 end;
|