Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Detecting spaces in txt file

Status
Not open for further replies.

DelphiBeginner

Programmer
Aug 13, 2003
1
ZA
Hi
sorry: silly question: how can I detect a spaces (in one line of text) when reading a text file? Essentially I want to read the individual words in a line.
Tx
 
hi

if pos(' ',line)> 0 then
//there's a space.

To actually pick out every word in the line, there's a little more to it and you wouldn't need pos.

eg.
Code:
procedure StripOutWords(searchstring : string; var ListofWords : TStringList);
  var tmpString : string;
      i : integer;
begin
  tmpString := '';
  ListOfWords.clear;
  i:= 1;
  while i <= length(SearchString) do
  begin
    if Uppercase(SearchString[i]) in ['A'..'Z','0'..'9']
      then TmpString := TmpString + SearchString[i]
    else
    begin
      ListOfWords.add(TmpString);
      TmpString:= '';
    end;
    inc(i);
  end;
  if tmpstring<> '' then
    ListofWords.add(TmpString);
end;
lou

 
There's an easier way to do it using a TStringList's DelimitedText property. Here's an example I knocked up which gets a line of text from an edit box and splits up the words. All you need to do is replace the Edit1.Text parameter with the line of your file:
Code:
  procedure GetWords(ALineOfText: String; var AListOfWords: TStringList);
  begin
    AListOfWords.DelimitedText := ALineOfText;
  end;

  procedure TForm1.Button1Click(Sender: TObject);
  var
    listOfWords: TStringList;
    counter: Integer;
  begin
    listOfWords := TStringList.Create;
    try
      GetWords(Edit1.Text, listOfWords);
      for counter := 0 to listOfWords.Count - 1 do
        ShowMessage(listOfWords.Strings[counter]);
    finally
      listOfWords.Free;
    end;
  end;

Hope this helps!

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
hi Clive

I like that property. Does it exist in Delphi 5 Prof as I can't find it?

lou

 
I'm using Delphi 6 Pro. I've had a good search in books and on the net and cannot find in which version the DelimitedText property was encorporated into the TStringList - sorry! I'm guessing that if it's not in yours then it's a new addition in Delphi 6. There may well be a SetDelimitedText property in Delphi 5 but I doubt it.

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
I think it's been there for a while (check Classes.pas), but not well documented because it probably has some bugs in the corner cases and they did not want to fix something that not many know about or use, and is easy enough to recreate.

Cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top