How to count spaces in a string (Java):
The following code shows you how to count number of spaces in a string.
Code
String str1 = "i proud to be a pakistani";
int spaceCount = 0;
for (int i = 0 ; i < str1.length() ; i++) {
Here, checking each character of string whether it is space.. and if it is space then counter plus by one:
if (Character.isWhitespace(str1.charAt(i))) {
spaceCount++;
}
}
System.out.println("Total Number Of Spaces In Str1 is : " + spaceCount);
Output of the program is:
Total Number Of Spaces In Str1 is : 5
ANOTHER WAY THROUGH SPACE ASCII VALUE:
String str1 = "proud to be a pakistani";
int spaceCount = 0;
for (int i = 0 ; i < str1.length() ; i++) {
Here, checking each character of string with the space ASCII value that is 32 and if it is equal then counter plus by one:
if (str1.charAt(i) == 32) {
spaceCount++;
}
}
System.out.println("Total Number Of Spaces In Str1 is : " + spaceCount);
Output of the program is:
Total Number Of Spaces In Str1 is : 4
0 comments:
Post a Comment