We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

# how to count char

on
Medium Priority
1,350 Views
how to count total of specified char in a text.

Say in my memo i have this:

sea is blue, sea near the sea shore. i like the sea

i want to count how many sea and the exist in the text.How

as i do as below
Problem of the code below is that it return line not char

``````var
text:string;
count : array[sea,the] of integer;

count[sea] := 0;
count[the] := 0;

text := memo.txt
if AnsiContainsStr(text,'sea') then
showmessage(IntToStr(inc(Count[sea]));
if AnsiContainStr(text,'the') then
showmessage(IntToStr(inc(Count[the]));
``````
Comment
Watch Question

## View Solution Only

Oracle dba
CERTIFIED EXPERT
Top Expert 2009

Commented:
use PosEx to find occurences :
``````function CountWords(aText, aWord: string): integer;
var n: Integer;
TempText, TempWord: string;
begin
Result := 0;
TempText := UpperCase(aText);
TempWord := UpperCase(aWord);
n := 1;
repeat
n := PosEx(TempWord, TempText, n);
if n > 0 then
Result := Result + 1;
until n = 0;
end;
``````

Commented:
what happen if in my text i have this
text = sea sea

the the repeat loop will loop forever

also
example i have text: sea sea

it return 1, why suppose i want it to be 2.

Commented:
also i try use this only

n := PosEx(TempWord, TempText, n);

example i have text: sea sea

it return 1, why suppose i want it to be 2.

Oracle dba
CERTIFIED EXPERT
Top Expert 2009
Commented:
i just typed it in the editor, forgot to test it
this is the altered version:
``````function CountWords(aText, aWord: string): integer;
var n: Integer;
TempText, TempWord: string;
begin
Result := 0;
TempText := UpperCase(aText);
TempWord := UpperCase(aWord);
n := 1;
repeat
n := PosEx(TempWord, TempText, n);
if n > 0 then
begin
Result := Result + 1;
n := n +1;
end;
until n = 0;
end;
``````

Not the solution you were looking for? Getting a personalized solution is easy.

Oracle dba
CERTIFIED EXPERT
Top Expert 2009

Commented:
ps: now i tested it and it works ...
if you want non case-sensitive:
``````function CountWords(aText, aWord: string; CaseSensitive: boolean = false): integer;
var n: Integer;
TempText, TempWord: string;
begin
Result := 0;
if not CaseSensitive then
begin
TempText := UpperCase(aText);
TempWord := UpperCase(aWord);
end
else
begin
TempText := aText;
TempWord := aWord;
end;
n := 1;
repeat
n := PosEx(TempWord, TempText, n);
if n > 0 then
begin
Result := Result + 1;
n := n +1;
end;
until n = 0;
end;
``````
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile