How to find all characters in a string whose appearance is greater than 2
6 answers
Sort sort will be extremely efficient for single-byte encodings, boundary case for double-byte encodings. For wider encodings this is not as efficient, but counting the array can be replaced with a hash table.
EDIT: By the way, this is too general a solution, doing just counting the phase and outputting the results on the fly will be more than enough.
+6
a source to share
Couldn't resist it.
- Store an internal 256-element array for each character (ASCII).
- Loop over the input line.
- Increment the counter for the given character using the ordinal value of the character as a direct access to the internal array.
Delphi implementation
Type
TCharCounter = class(TObject)
private
FCounts: array[0..255] of byte;
public
constructor Create(const Value: string);
function Count(const AChar: Char): Integer;
end;
{ TCharCounter }
constructor TCharCounter.Create(const Value: string);
var
I: Integer;
begin
inherited Create;
for I := 1 to Length(Value) do
Inc(FCounts[Ord(Value[I])]);
end;
function TCharCounter.Count(const AChar: Char): Integer;
begin
Result := FCounts[Ord(AChar)];
end;
+1
a source to share