2013-03-08 47 views

risposta

27

È possibile utilizzare questa semplice funzione:

function OccurrencesOfChar(const S: string; const C: char): integer; 
var 
    i: Integer; 
begin 
    result := 0; 
    for i := 1 to Length(S) do 
    if S[i] = C then 
     inc(result); 
end; 
+0

non posso farlo in un linea singola? –

+10

@NareshKumar: Sì, ovviamente: 'OccurrencesOfChar (myString, ',')' –

+2

+1 ma chr è un nome scadente poiché ha già un significato. Suggerisco C –

15

E per chi preferisce il ciclo enumeratore nelle versioni di Delphi moderne (non meglio rispetto alla soluzione accettata da Andreas, solo una soluzione alternativa):

function OccurrencesOfChar(const ContentString: string; 
    const CharToCount: char): integer; 
var 
    C: Char; 
begin 
    result := 0; 
    for C in ContentString do 
    if C = CharToCount then 
     Inc(result); 
end; 
8

Questo può fare il lavoro per se non stai manipolazione testo di grandi dimensioni

...

uses RegularExpressions; 

...

function CountChar(const s: string; const c: char): integer; 
begin 
Result:= TRegEx.Matches(s, c).Count 
end; 
+0

Perché non dovrebbe essere buono su Delphi? Le espressioni regolari sono abbastanza buone per gestire corpi di testo di grandi dimensioni. –

15

Anche se una risposta è già stata accettata, sto postando la funzione più generale di seguito perché lo trovo così elegante. Questa soluzione serve a contare le occorrenze di una stringa piuttosto che un carattere.

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

+1 per interpretazione artistica. –

+1

Interessante punto di vista! Forse potresti semplificare la prima istruzione a 'Risultato: = Pos (Sottotesto, Testo); se Risultato> 0 allora ... '[+1] – TLama

+0

Questo è bellissimo Robert. – Sam

0

È possibile utilizzare il beneficio della funzione StringReplace come:

function OccurencesOfChar(ContentString:string; CharToCount:char):integer; 
begin 
    Result:= Length(ContentString)-Length(StringReplace(ContentString, CharToCount,'', [rfReplaceAll, rfIgnoreCase])); 
end;