Can you use regular expression ? Here is an example
Let stick with loop each char
public class MyClass {
public static void main(String args[]) {
startWithCapital("Ali From Saudi araBia YayYY");
}
public static int startWithCapital(String M) {
int p = 0;
for (int i = 0; i < M.length(); i++) {
if (i == 0) {
String names = M.substring(i, i + 1);
char a = names.charAt(i);
if (Character.isUpperCase(a)) {
p++;
}
}
if (i >= 1) {
if (Character.isUpperCase(M.charAt(i))) {
if (M.charAt(i-1) == ' ') {
p++;
}
}
}
}
System.out.println("The num of words starting with a capital letter = " + p + " words\n");
return 0;
}
}
public class MyClass {
public static void main(String args[]) {
String M = "Ali From Saudi araBia Yay";
int p = 0;
String[] parts = M.split(" ");
for (String part : parts) {
System.out.println(part);
if (Character.isUpperCase(part.charAt(0))) {
p++;
}
}
System.out.println("The num of words starting with a capital letter = " + p + " words\n");
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyClass {
public static void main(String args[]) {
Pattern p = Pattern.compile("[A-Z]\\S+");
Matcher m = p.matcher("Ali From Saudi arabia YaY");
int count = 0;
while (m.find())
count++;
System.out.println(count);
}
}
Output:
The num of words starting with a capital letter = 4 words
Test it out:
Count Uppercase[
^]
reference:
Java: Find number of regex matches in a String | Programming.Guide[
^]