Mirror

How to use TStrings.DelimitedText to separate a comma delimited string (Views: 100)


Problem/Question/Abstract:

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.

{Function IScan
Parameters:
ch: Character to scan for
S : String to scan
fromPos: first character to scan
Returns: position of next occurence of character ch, or 0, if none found
Description: Search for next occurence of a character in a string.
Error Conditions: none
Created: 11/27/96 by P. Below}

function IScan(ch: Char; const S: string; fromPos: Integer): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := fromPos to Length(S) do
  begin
    if S[i] = ch then
    begin
      Result := i;
      Break;
    end;
  end;
end;

{Procedure SplitString
Parameters:
S: String to split
separator: character to use as separator between substrings
substrings: list to take the substrings
Description:
Isolates the individual substrings and copies them into the passed stringlist. Note that we only add to the list, we do not clear it first! If two separators follow each other directly an empty string will be added to the list.
Error Conditions:
will do nothing if the stringlist is not assigned
Created: 08.07.97 by P. Below}

procedure SplitString(const S: string; separator: Char; substrings: TStringList);
var
  i, n: Integer;
begin
  if Assigned(substrings) and (Length(S) > 0) then
  begin
    i := 1;
    repeat
      n := IScan(separator, S, i);
      if n = 0 then
        n := Length(S) + 1;
      substrings.Add(Copy(S, i, n - i));
      i := n + 1;
    until
      i > Length(S);
  end;
end;

<< Back to main page