String-Based Interview Questions with Java & C++ Solutions
1. Count Digits and Alphabetic Characters in a String
Description:
Given a string, count how many characters are digits (0-9) and how many are alphabetic letters (A-Z or a-z).
Ignore all other types of characters.
Sample Input:
Input: "Shubham123!@#45"
Expected Output:
Digits: 5
Alphabets: 7
1.1. Java Brute Force
public class StringCharacterCount {
public static void main(String[] args) {
String str = "Shubham123!@#45";
int digits = 0, letters = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if ((ch >= '0' && ch <= '9')) {
digits++;
} else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
letters++;
}
}
System.out.println("Digits: " + digits);
System.out.println("Alphabets: " + letters);
}
}
1.2. C++ Brute Force
#include <iostream>
using namespace std;
int main() {
string str = "Shubham123!@#45";
int digits = 0, letters = 0;
for (char ch : str) {
if (ch >= '0' && ch <= '9') {
digits++;
} else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
letters++;
}
}
cout << "Digits: " << digits << endl;
cout << "Alphabets: " << letters << endl;
return 0;
}
String-Based Interview Questions with Java & C++ Solutions
1.3. Java Optimal
public class StringCharacterCountOptimal {
public static void main(String[] args) {
String str = "Shubham123!@#45";
int digits = 0, letters = 0;
for (char ch : str.toCharArray()) {
if (Character.isDigit(ch)) {
digits++;
} else if (Character.isLetter(ch)) {
letters++;
}
}
System.out.println("Digits: " + digits);
System.out.println("Alphabets: " + letters);
}
}
1.4. C++ Optimal
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string str = "Shubham123!@#45";
int digits = 0, letters = 0;
for (char ch : str) {
if (isdigit(ch)) {
digits++;
} else if (isalpha(ch)) {
letters++;
}
}
cout << "Digits: " << digits << endl;
cout << "Alphabets: " << letters << endl;
return 0;
}