繁体   English   中英

在Delphi中查找和计算字符串中的单词?

[英]Find and Count Words in a String in Delphi?

我有一个包含许多单词的字符串。 如何查找和计算特定单词出现的总次数?

 E.g "hello-apple-banana-hello-pear"

我将如何在上面的例子中找到所有“你好”?

谢谢。

在Delphi XE中,您可以使用StrUtils.SplitString

像这样的东西

var
    Words: TstringDynArray;
    Word: string;
    WordCount: Integer;
begin
    WordCount := 0;
    Words := SplitString('hello-apple-banana-hello-pear', '-');
    for Word in Words do
    begin
        if Word = 'hello' then
            inc(WordCount);
    end;

这完全取决于您如何定义单词以及您希望从中提取单词的文本。 如果“单词”是空格之间的所有内容,或者在您的示例中为“ - ”,那么它就变成了一个相当简单的任务。 但是,如果你想处理带连字符的单词,缩写,收缩等,那么它就变得更加困难了。

请更多信息。

编辑:重新阅读你的帖子,如果你给出的例子是你想要的唯一一个,那么我建议:

function CountStr(const ASearchFor, ASearchIn : string) : Integer;
var
  Start : Integer;
begin
  Result := 0;
  Start := Pos(ASearchFor, ASearchIn);
  while Start > 0 do
    begin
      Inc(Result);
      Start := PosEx(ASearchFor, ASearchIn, Start + 1);
    end;
end;

这将捕获一系列字符的所有实例。

我确信有很多代码可以做这类事情,但在Generics.Collections.TDictionary<K,V>的帮助下,你可以轻松完成。

program WordCount;

{$APPTYPE CONSOLE}

uses
  SysUtils, Character, Generics.Collections;

function IsSeparator(const c: char): Boolean;
begin
  Result := TCharacter.IsWhiteSpace(c);//replace this with whatever you want
end;

procedure PopulateWordDictionary(const s: string; dict: TDictionary<string, Integer>);

  procedure AddItem(Item: string);
  var
    Count: Integer;
  begin
    if Item='' then
      exit;
    Item := LowerCase(Item);
    if dict.TryGetValue(Item, Count) then
      dict[Item] := Count+1
    else
      dict.Add(Item, 1);
  end;

var
  i, len, Start: Integer;
  Item: string;
begin
  len := Length(s);
  Start := 1;
  for i := 1 to len do begin
    if IsSeparator(s[i]) then begin
      AddItem(Copy(s, Start, i-Start));
      Start := i+1;
    end;
  end;
  AddItem(Copy(s, Start, len-Start+1));
end;

procedure Main;
var
  dict: TDictionary<string, Integer>;
  pair: TPair<string, Integer>;
begin
  dict := TDictionary<string, Integer>.Create;
  try
    PopulateWordDictionary('hello  apple banana Hello pear', dict);
    for pair in dict do
      Writeln(pair.Key, ': ', pair.Value);
  finally
    dict.Free;
  end;
end;

begin
  try
    Main;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

输出:

hello: 2
banana: 1
apple: 1
pear: 1

注意:我正在使用Delphi 2010并且没有可用的SplitString()

我在网上看到的一个非常聪明的实现:

{ Returns a count of the number of occurences of SubText in Text }
function CountOccurences( const SubText: string;
                          const Text: string): Integer;
begin
  if (SubText = '') OR (Text = '') OR (Pos(SubText, Text) = 0) then
    Result := 0
  else
    Result := (Length(Text) - Length(StringReplace(Text, SubText, '', [rfReplaceAll]))) div  Length(subtext);
end;  { CountOccurences }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM