joh*_*n12 4 delphi string algorithm substring
我有一个包含许多单词的字符串.如何查找和计算特定单词出现的总次数?
E.g "hello-apple-banana-hello-pear"
Run Code Online (Sandbox Code Playgroud)
我将如何在上面的例子中找到所有"你好"?
谢谢.
Mik*_*son 16
在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;
Run Code Online (Sandbox Code Playgroud)
这完全取决于您如何定义单词以及您希望从中提取单词的文本.如果"单词"是空格之间的所有内容,或者在您的示例中为" - ",那么它就变成了一个相当简单的任务.但是,如果你想处理带连字符的单词,缩写,收缩等,那么它就变得更加困难了.
请更多信息.
编辑:重新阅读你的帖子,如果你给出的例子是你想要的唯一一个,那么我建议:
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;
Run Code Online (Sandbox Code Playgroud)
这将捕获一系列字符的所有实例.
我确信有很多代码可以做这类事情,但是很容易在你的帮助下自己完成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.
Run Code Online (Sandbox Code Playgroud)
输出:
hello: 2
banana: 1
apple: 1
pear: 1
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用Delphi 2010并且没有SplitString()可用的.
| 归档时间: |
|
| 查看次数: |
9584 次 |
| 最近记录: |