1

Hy! What is the best way to find the first two Word in a string? For example, my string is an adress like : Cross Keys st 13. I need only 'Cross Keys' from it. Should I count the words in the string or there a better solution for that?

I can get the first and the last Word easily. I am new in Delphi. Thanks for the suggestions.

procedure SampleForm.ButtonClick(Sender: TObject);
var
  st: string;
  myString : string;
  C: integer;
begin
  st := Cross Keys st 13;
  C:=LastDelimiter(' ',st);

  myString := Copy(st,1,pos(' ',st)-1);
  mystring:=Copy(st,C+1,length(st)-C);
Steve88
  • 2,366
  • 3
  • 24
  • 43
  • 1
    Look at the first answer here: http://stackoverflow.com/questions/2625707/split-a-string-into-an-array-of-strings-based-on-a-delimiter – Hampus Sep 30 '15 at 20:16
  • 2
    If you can get the first word, then you can surely get the second by simply repeating whatever you do for the first. Your question asks for something "better" than what you have. Please describe what you mean by "better." – Rob Kennedy Sep 30 '15 at 20:19
  • 2
    What if there is only one word? – David Heffernan Sep 30 '15 at 20:27

2 Answers2

1

The scope was delphi XE so string.split doesn't work. Instead you can use IStringTokenizer from HTTPUtil. Like this:

uses
  HTTPUtil;

function GetFirstNWrods(const str: string; const delim: string; Numwords: Integer): string;
var
  Tokenizer: IStringTokenizer;
begin
  Result := '';
  Tokenizer := StringTokenizer(str, delim);
  while (Tokenizer.hasMoreTokens) and (Numwords > 0) do
  begin
    Result := Result + Tokenizer.nextToken + delim;
    Dec(Numwords)
  end;

  System.Delete(Result, Length(Result) - Length(delim) + 1, Length(delim));
end;

Example of how to call the function:

procedure TForm1.FormCreate(Sender: TObject);
begin
  Caption := GetFirstNWrods('1 2 3 4', ' ', 2);
end;
Jens Borrisholt
  • 6,174
  • 1
  • 33
  • 67
0
procedure TForm9.Button1Click(Sender: TObject);
begin
 ShowMessage(someWord('first second and ...',1));    // show:  first
 ShowMessage(someWord('first second and ...',2));    //show: second
end;

function TForm9.someWord(sir: string; oneWord: integer): string;
var
  myArray: TArray<string>;
begin
  myArray := sir.Split([' ']); //myArray it's an Tstring of Words from sir
  case oneWord of
    1:
      result := myArray[low(myArray)];   // result is first elemnt of myArray; low(myArray)=0
    2:
      begin
        if high(myArray) > 0 then     // high(myArray) index of last element of myArray
          result := myArray[low(myArray) + 1]   // result is second element of myArray
        else
          result := '';
      end;
  end;
end;
GrigoreT
  • 1
  • 2