Home » Java programs

Java program to count number of digits in a string



In this article of java program, we will learn how to count the number of digits in a string?
Submitted by Jyoti Singh, on October 05, 2017

Given a string and we have to count total number of digits in it using Java.

Example:

Input string: "code2017"
Output:
Number of digits: 4

In this code we have one input:

  1. An int input (no. of test cases or more clearly the number of strings user wants to check (say 5 i.e user wants to check 5 strings and the program will continue for 5 inputs).
  2. A string input (It will be a string entered by the user which needs to be checked).

For each string we will have two outputs

The number of digits in string

Consider the program: It will take number of inputs, string and print total number of digits.


import java.util.Scanner;

public class CheckDigits {

	public static void main(String[] args) {
		Scanner Kb=new Scanner(System.in);
		System.out.println("How man strings u want to check?");
		//Take the input of no. of test cases
		int t=Kb.nextInt();
		//looping until the test cases are zero
		while(t-->0){
			//Input the string
			System.out.println("Enter the string!");
			String s=Kb.next();
			//counter to count the number of digits in a string
			int digits=0;
			//looping until the string length is zero
			for(int i=0;i<s.length();i++){
				//isDigit is a function of Character class it checks a particular char that whether it is a digit or not
				if(Character.isDigit(s.charAt(i))){
					//counter digit will be incremented each time when a character will be a digit
					digits++;
				}
			}
			//prints the number of digits in a string
			System.out.println(digits);
		}
		System.out.println();
	}

}





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.