-1
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?

N00b Pr0grammer
  • 4,503
  • 5
  • 32
  • 46
Ties
  • 9
  • 1

1 Answers1

0

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.

Eric Gumba
  • 435
  • 3
  • 16