Skip to main content

Posts

Showing posts with the label digit

Separate digits, characters and special characters from a mixed string

 Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import java.util.Scanner; public class Separate{ public static void main (String []args){ Scanner sc = new Scanner(System. in ); System. out . println ( "Enter a mixed string:" ); String mixed = sc. next (); String chars= "" , digits= "" , spec_chars= "" ; for ( int i= 0 ; i<mixed. length (); i++){ char ch = mixed. charAt (i); if (ch>= 'a' && ch<= 'z' || ch>= 'A' && ch<= 'Z' ) chars += ch; else if (ch>= '0' && ch<= '9' ) digits += ch; else spec_chars += ch; } System. out . println ( "Characters: " +char...

Check if a string contains only digits

 In this program, we have to check whether a string consists of only digits (i.e. 0,1,2.....9). eg:- "qwerty" ( the given string contains characters, not digits ) print No. "123e" ( there is a character present in the given string ) print No. "995765" (the given string contains only digits, no any characters are present ) print Yes. How to approach :-   Traverse through each character of the string and for each character check whether it is a digit or not. Now the question is " How to check a character in the given string is alphabet or digit ? " We can check this by 2 methods :-- 1. Check using ASCII value:--      If the ASCII value of a character is between 48 to 57 (including both 48 and 57)  then it is a digit (0,1,2,3,....,8,9).           If the ASCII value of a character is between 65 to 90 (including both 65 and 90)  then it is a uppercase alphabet (A,B,C,D,....,Y,Z)....