Author: Jonas Bilinkevicius
I am trying to use TStrings.DelimitedText to separate a comma delimited string. The
trouble is (some of my strings contain spaces, for example a person's address),
with TStrings.DelimitedText it seems to have the space character set as a delimiter
as well as the character that I specify. How do I stop it from doing this?
Answer:
The substrings in the comma-separated list have to be enclosed in the
TStrings.QuoteChar for this to work properly. The way TStrings.SetDelimitedText has
been written it will not only break on the Delimiter character but also on any
character in the range #1..' ' when they appear outside a quoted string. The
SplitString routine below does not suffer from this problem but it does not handle
delimiters inside quoted strings.
1 {Function IScan2 Parameters:3 ch: Character to scan for4 S : String to scan5 fromPos: first character to scan6 Returns: position of next occurence of character ch, or 0, if none found7 Description: Search for next occurence of a character in a string.8 Error Conditions: none9 Created: 11/27/96 by P. Below}10 11 function IScan(ch: Char; const S: string; fromPos: Integer): Integer;
12 var13 i: Integer;
14 begin15 Result := 0;
16 for i := fromPos to Length(S) do17 begin18 if S[i] = ch then19 begin20 Result := i;
21 Break;
22 end;
23 end;
24 end;
25 26 {Procedure SplitString27 Parameters:28 S: String to split29 separator: character to use as separator between substrings30 substrings: list to take the substrings31 Description:32 Isolates the individual substrings and copies them into the passed stringlist. Note 33 that we only add to the list, we do not clear it first! If two separators follow 34 each other directly an empty string will be added to the list.35 Error Conditions:36 will do nothing if the stringlist is not assigned37 Created: 08.07.97 by P. Below}38 39 procedure SplitString(const S: string; separator: Char; substrings: TStringList);
40 var41 i, n: Integer;
42 begin43 if Assigned(substrings) and (Length(S) > 0) then44 begin45 i := 1;
46 repeat47 n := IScan(separator, S, i);
48 if n = 0 then49 n := Length(S) + 1;
50 substrings.Add(Copy(S, i, n - i));
51 i := n + 1;
52 until53 i > Length(S);
54 end;
55 end;