-5

I'd like to write OOP reusable code that does the following (just one solution):

  1. Count number of occurrences of specific letter in string: e.g. 'h' in "Hello"=>2
  2. Count number of occurrences of specific digit in a number e.g. 4 in 32456445 =>3
  3. Do the sum of two numbers: e.g. 5,4 =>9

If the required actions where Add & subtract, I can do this:

public delegate int BinaryOp(int x, int y);


public class SimpleMath
{
  public static int Add(int x, int y) { return x + y; }
  public static int Sub(int x, int y) { return x - y; }
}

Then do this for the Add (and something similar for Sub):

 BinaryOp b = new BinaryOp(SimpleMath.Add);

My question is: what's the best solution for doing count specific letter in a string, count of specific digit in number, and Add(num1+num2) (best single OOP solution)?

Count('l',"Hello") => 2

Count(4,32456445 ) =>3

Add(5,4) =>9

  • 4
    why do you have all that complicated delegate stuff – pm100 Mar 09 '22 at 22:46
  • @JohnsonBill: For your first problem there is a very detailed answer on SO: [Maybe this post will help you](https://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-actually-a-char-within-a-string). Also for you second problem [there is this SO Answer](https://stackoverflow.com/questions/37719522/efficient-way-to-count-the-number-of-appearances-of-a-digit-in-a-number) – Martin Mar 09 '22 at 23:31
  • 1
    Does this answer your question? [Efficient way to count the number of appearances of a digit in a number](https://stackoverflow.com/questions/37719522/efficient-way-to-count-the-number-of-appearances-of-a-digit-in-a-number) – Martin Mar 09 '22 at 23:34

1 Answers1

2

First one:

static int CountChar(string str, char chr)
{
    return str.Count(c => c == chr);
}

Second one:

static int CountDigits(int num, int findNum)
{
    if (findNum < 0 || findNum > 9)
    {
        throw new InvalidOperationException("must be single digit");
    }
    return CountChar(num.ToString(), findNum.ToString()[0]);
}

and still 'why that complicated delegate stuff'?

Martin
  • 3,096
  • 1
  • 26
  • 46
pm100
  • 48,078
  • 23
  • 82
  • 145
  • 3
    There's an overload of `Count` that accepts a condition, so the first method can be simplified to use `return str.Count(c=>c==chr);`. – printf Mar 09 '22 at 23:20
  • @printf - I thought so but wasnt sure - too lazy to check - ty – pm100 Mar 09 '22 at 23:26