[英]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.