Extract Digits from String

Easy
0/40
0 upvote

Problem statement

You are given a string S which may contain a mix of uppercase letters, lowercase letters, digits, symbols, and spaces.


Your task is to create a new string that consists of only the digit characters ('0' through '9') from the original string S. The digits in the new string must appear in the same relative order as they did in the original string.


If no digits are present in the input string, your function should return an empty string.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first and only line of input contains a single string S.


Output Format:
Your function should return a single string containing only the extracted digits. The runner code will handle printing this returned value.


Notes:
The most straightforward approach is to iterate through the input string character by character and use a built-in helper function (like isdigit()) to check if the character is a numeric digit.
Sample Input 1:
abc123xyz


Sample Output 1:
123


Explanation for Sample 1:
The characters '1', '2', and '3' are the only digits in the string. They are extracted and concatenated in their original order.


Sample Input 2:
Hello! 123 World-456?


Sample Output 2:
123456


Explanation for Sample 2:
The program iterates through the string, ignoring all non-digit characters and collecting the digits 1, 2, 3, 4, 5, 6 in the order they appear.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
0 <= length of S <= 10^5
The string S can contain any standard ASCII characters.
Time Limit: 1 sec
Approaches (1)
Brute Force
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Extract Digits from String
Full screen
Console