fork download
  1. #include <stdio.h>
  2.  
  3. int count_digits(const char *str) {
  4. int count = 0;
  5. for (int i = 0; str[i] != '\0'; i++) {
  6. if (str[i] >= '0' && str[i] <= '9') {
  7. count++;
  8. }
  9. }
  10. return count;
  11. }
  12.  
  13. int main() {
  14. // 数字が含まれる文字列
  15. const char *test_string1 = "abc123def45";
  16. int digits1 = count_digits(test_string1);
  17. printf("文字列 '%s' の数字の個数: %d\n", test_string1, digits1);
  18.  
  19. // 数字のみ
  20. const char *test_string2 = "9876543210";
  21. int digits2 = count_digits(test_string2);
  22. printf("文字列 '%s' の数字の個数: %d\n", test_string2, digits2); // 期待値: 10
  23.  
  24. // 数字が含まれない文字列
  25. const char *test_string3 = "hello_world!";
  26. int digits3 = count_digits(test_string3);
  27. printf("文字列 '%s' の数字の個数: %d\n", test_string3, digits3);
  28.  
  29. // 空文字列
  30. const char *test_string4 = "";
  31. int digits4 = count_digits(test_string4);
  32. printf("文字列 '%s' の数字の個数: %d\n", test_string4, digits4);
  33.  
  34. // 数字と記号
  35. const char *test_string5 = "1a!2@b#3$";
  36. int digits5 = count_digits(test_string5);
  37. printf("文字列 '%s' の数字の個数: %d\n", test_string5, digits5);
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5292KB
stdin
Standard input is empty
stdout
文字列 'abc123def45' の数字の個数: 5
文字列 '9876543210' の数字の個数: 10
文字列 'hello_world!' の数字の個数: 0
文字列 '' の数字の個数: 0
文字列 '1a!2@b#3$' の数字の個数: 3