String txt="Hello world";
int count;
for(int x = 0; x <= txt.length(); x++) {
if (txt.charAt(x) == ' ') {
count++;
}
}
My app was force closing after declaring the charAt()
, is there any problem with this? & how can i fix it?
String txt="Hello world";
int count;
for(int x = 0; x <= txt.length(); x++) {
if (txt.charAt(x) == ' ') {
count++;
}
}
My app was force closing after declaring the charAt()
, is there any problem with this? & how can i fix it?
Indices start at 0.
For example,
String str = "foo"
Is a string of length 3. However, when we count the characters of the string we start at 0 which corresponds to 'f' and end at 2 which corresponds to 'o'.
The code,
String str = "foo";
for(int i = 0; i <= str.length(); i++) {
// ...
}
Is incorrect because it counts from 0 to 3.
String str = "foo";
for(int i = 0; i < str.length(); i++) {
// ...
}
is correct because it counts from 0 to 2.