Tutorialspoint
Problem
Solution
Submissions

String Contains Only Digits

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a C# program to check if a given string contains only digits (0-9). The function should return "true" if the string contains only digits and "false" otherwise. An empty string should return "false".

Example 1
  • Input: str = "123456"
  • Output: true
  • Explanation:
    • Step 1: Check if the string is null or empty (it's not).
    • Step 2: Iterate through each character in the string "123456".
    • Step 3: Check if each character is a digit between '0' and '9' inclusive.
    • Step 4: All characters ('1', '2', '3', '4', '5', '6') are digits.
    • Step 5: Return true since all characters in the string are digits.
Example 2
  • Input: str = "12a34"
  • Output: false
  • Explanation:
    • Step 1: Check if the string is null or empty (it's not).
    • Step 2: Iterate through each character in the string "12a34".
    • Step 3: Check if each character is a digit between '0' and '9' inclusive.
    • Step 4: The character 'a' at index 2 is not a digit.
    • Step 5: Return false immediately since not all characters in the string are digits.
Constraints
  • 0 ≤ str.length ≤ 10⁴
  • str consists of ASCII characters
  • Time Complexity: O(n)
  • Space Complexity: O(1)
StringsControl StructuresEYPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Check each character of the string to determine if it's a digit
  • Use built-in C# functions to simplify the solution
  • Handle edge cases like empty strings
  • Consider using character code comparisons or regex for alternative solutions
  • Return false as soon as a non-digit character is found for optimization

Steps to solve by this approach:

 Step 1: Handle edge case of empty string by returning false.
 Step 2: Iterate through each character of the string.
 Step 3: Check if each character is within the ASCII range of digits ('0' to '9').
 Step 4: Return false immediately upon encountering a non-digit character.
 Step 5: If all characters are digits, return true.

Submitted Code :