如何在字符串中找到前两个单词

时间:2015-09-30 20:08:44

标签: delphi delphi-xe

HY!在字符串中查找前两个Word的最佳方法是什么?例如,我的字符串是一个地址,如:Cross Keys st 13.我只需要'Cross Keys'。我应该计算字符串中的单词还是有更好的解决方案?

我可以轻松获得第一个和最后一个Word。我是Delphi的新手。谢谢你的建议。

     jQuery(document).ready(function($){
         jQuery('.items').scroll(function() {
            var top = $(this).children().first();
            $(this).children().each(function(){
                var offset = $(this).offset().top;
                if(offset < 0 && offset >= -$(this).height()){
                    top = $(this);
                    return false; //"break"
                }
            });

            console.log(top.attr('id'));
        });
    });

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

范围是delphi XE,因此string.split不起作用。相反,您可以使用IStringTokenizer中的HTTPUtil。像这样:

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;

如何调用该函数的示例:

procedure TForm1.FormCreate(Sender: TObject);
begin
  Caption := GetFirstNWrods('1 2 3 4', ' ', 2);
end;