在文本中找到单词后获取整个单词串

时间:2017-11-12 20:07:54

标签: function delphi delphi-xe

我在开发此功能时遇到问题,我有这个文字..

Testing Function
ok
US.Cool
rwgehtrhjyw54 US_Cool
fhknehq is ryhetjuy6u24
gflekhtrhissfhejyw54i

我的职能:

function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
begin
 Result := 0;
 for i:= 1 to Length(sTheString) do
   begin
    x := Copy(sTheString,i,Length(sWordToFind));
    if X = sWordToFind then
      begin
        if X.Length > sWordToFind.Length then
         begin
          Result := 100;
          break;
         end else

         begin
          Result := i;
          break;
         end;
       end;
   end;
end;

现在,我希望X为US.Cool,但在此总是= US,因为我想检查sWordToFind和X的长度。

2 个答案:

答案 0 :(得分:2)

我花了几次关于你的想法,所以我写了下面的代码,但这不是开发一个开始搜索的好方法。通过一些研究,您可以找到内置函数,从而提供更好的性能。您可以尝试StrUtils.SearchBuf Function它将提供完整的函数字符串搜索。

无论如何,这段代码正在使用SPACE分隔符,我希望它对你有用:

function TForm5.FindWordInString(sWordToFind, sTheString : String): Integer;
var
i : Integer; x:String;
flag : Boolean;
begin
 Result := 0;
 i := 1;
 flag := False;
 while True do
   begin
   if i > Length(sTheString) then  Break;

   if not flag then
       x := Copy(sTheString,i,Length(sWordToFind))
   else
   begin

       if sTheString[i] = ' ' then Break;
       x := x + sTheString[i];
   end;

    if (X = sWordToFind)  then
      begin
        flag := True;
        if (X.Length >= sWordToFind.Length) and
           (sTheString[i + Length(sWordToFind)]  = ' ') then
          break
        else
          i := i +  Length(sWordToFind) -1;

       end;


     i := i + 1;
   end;
   Result :=  Length(x);
end; 

答案 1 :(得分:2)

在澄清之后,这个问题是关于通过字符串中的起始子字符串搜索单词的长度。例如,当有这样的字符串时:

fhknehq is ryhetjuy6u24

当您使用以下子字符串为上述字符串执行所需的函数时,您应该得到如下结果:

hknehq → 0 → substring is not at the beginning of a word
fhknehq → 7 → length of the word because substring is at the beginning of a word
yhetjuy6u24 → 0 → substring is not at the beginning of a word
ryhetjuy6u24 → 12 → length of the word because substring is at the beginning of a word

如果是这样,我会这样做:

function GetFoundWordLength(const Text, Word: string): Integer;
const
  Separators: TSysCharSet = [' '];
var
  RetPos: PChar;
begin
  Result := 0;
  { get the pointer to the char where the Word was found in Text }
  RetPos := StrPos(PChar(Text), PChar(Word));
  { if the Word was found in Text, and it was at the beginning of Text, or the preceding
    char is a defined word separator, we're at the beginning of the word; so let's count
    this word's length by iterating chars till the end of Text or until we reach defined
    separator }
  if Assigned(RetPos) and ((RetPos = PChar(Text)) or CharInSet((RetPos - 1)^, Separators)) then
    while not CharInSet(RetPos^, [#0] + Separators) do
    begin
      Inc(Result);
      Inc(RetPos);
    end;
end;