Issue
(Java) How can I count the number of tab and space before the first character of a string
Assume that a string
String line = " Java is good."
There are totally 10 spaces in this string. However, how can I count the number of tab and space before the first character "J" only? There are 8 spaces before the first character "J" only.
Solution
How about:
String s = " Java is good.";
int total = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isWhitespace(s.charAt(i))) {
total++;
} else {
break;
}
}
System.out.println(total);
Or
String s = " Java is good.";
int total = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == ' ' || ch == '\t') {
total++;
} else {
break;
}
}
System.out.println(total);
Answered By - Ahmed Ashour
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)