public class Calcharnumbers {public
static void Main (string[] args) {
System.out.println ("Please enter a string:");
Scanner sc = new Scanner (system.in);
String str = Sc.nextline ();//This Must be sc.nextline (); The input string in Java can also be sc.next (), but reading a space in this way stops
int alphanum = 0;
int spacenum = 0;
int digtnum = 0;
int othernum = 0;
for (int i=0;i<str.length (); i++) {
if (Str.charat (i) >= ' 0 ' &&str.charat (i) <= ' 9 ') {
digtnum+ +;
} else if ((Str.charat (i) >= ' a ' &&str.charat (i) <= ' z ') | | (Str.charat (i) >= ' A ' &&str.charat (i) <= ' Z ')) {
alphanum++;
} else if (Str.charat (i) = = ') {
spacenum++
} else{
othernum++
}
}
System.out.println ("Letter:" +alphanum+ ", Number:" +digtnum+ ", Space:" +spacenum+ ", other characters:" +othernum);
}
The following are implemented with regular expressions:
Import Java.util.Scanner;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;
Counts the number of letters, spaces, numbers, and other characters in a string public
class Calcharnumbers {public
static void Main (string[] args) {
System.out.println ("Please enter a string:");
Scanner sc = new Scanner (system.in);
String s = sc.nextline ();
String regex1 = "[a-z| A-z] ";
String regex2 = "[0-9]";
Calcharnumbers C = new Calcharnumbers ();
int a1 = C.string (S, regex1);
System.out.println ("Number of digits:" +a1);
int a2 = c.string (S, regex2);
System.out.println ("Number of Letters:" +A2);
int a3 = c.string (S, "");
System.out.println ("Number of Spaces:" +A3);
int a4 = s.length ()-a1-a2-a3;
System.out.println ("Number of other characters:" +a4);
}
public int string (string s, string patterns) {
pattern p = pattern.compile (patterns);//To compile the given regular expression into the schema.
Matcher m = P.matcher (s);//create a match between the given input and this pattern.
int i = 0;
while (M.find ()) {//attempts to find the next subsequence of the input sequence that matches the pattern.
i++;
}
return i;
}
}