Pages

Friday, 8 March 2013

How to count number of occurrences of a character in a string in Delphi XE2? Solution by Stackoverflow Delphi Experts


How to count number of occurrences of a character in a string in Delphi XE2? Solution by Stackoverflow Delphi Experts

Question:
Assume that I have the following string and would like to count the number of commas in it:
S := '1,2,3';
Then I would like to obtain 2 as the result.

I had asked above question on stackoverflow and received very informative and interesting responses from delphi experts available on stackoverflow. Basically my problem was that the above string '1,2,3' was in a column of a table in database. I had to fetch that column and count the number of digits. So, I planned to count the number of commas and increment it by one. But I stuck on the point "How to count number of occurrences of comma in a string in Delphi XE2?" Then I asked above question and immediately in one or two minutes I received answer s which saved my time.

Answers:

1. Andreas Rejbrand (SO Reputation at the time of writing: 45481) was the first expert to give me a simple answer which I accepted later on. He gave me following solution:

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;

2. Ken White (SO Reputation at the time of writing: 43204) gave me an alternative solution which was also very simple.

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;

3. Raul (SO Reputation at the time of writing: 232) gave me the solution based on regular expressions which was even shorter than other approaches.

uses RegularExpressions;
...

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

4. Robert Frank (SO Reputation at the time of writing: 3841) gave me the solution which was not directly targeting my problem but was a general solution for problems like I faced. So, I liked and up voted this solution also.

{ 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 }

Thanks all the stackoverflow delphi experts for helping me out and saving my day. 

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.