For the length of the string, I am trying to do something like this. My code is as follows..
I keep getting
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 60 at java.lang.String.charAt(String.java:558) at <CLASSNAME>.main(<CLASSNAME>.java:9)
charAt(60) will be the last character in the string.
Let's try this one again....
charAt(0) will be the first character in the string. charAt(1) will be the second character in the string. charAt(2) will be the third character in the string.
The point marc is trying to make is that String indexes start at 0. Therefore for a nonempty String of length x, the first character is always at index 0, the last character is always at index (x - 1).
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Originally posted by Avi Sridhar: ...charAt(60) will be the last character in the string...
No.
The 1st char is not charAt(1). It is charAt(0). The 2nd char is not charAt(2). It is charAt(1). The 3rd char is not charAt(3). It is charAt(2). And so on.
So if the String has 60 chars, the 60th char is not charAt(60).
(Whoops... Posted before I saw Henry's and Garrett's responses. So it's redundant, but hopefully clear now.) [ June 20, 2008: Message edited by: marc weber ]
Originally posted by Rob Prime: And unlike C strings (char arrays), Java strings are NOT NULL terminated (\0).
Thanks everyone for your thoughts. it really helped.
I am going to use this instead
and we will get 60 chars there.
Paul Sisco
Greenhorn
Joined: Jun 15, 2008
Posts: 11
posted
0
Originally posted by Avi Sridhar:
Thanks everyone for your thoughts. it really helped.
I am going to use this instead
and we will get 60 chars there.
This isn't exactly about your question. Hopefully I am not out of place asking this... Are you sure the string length will always be 60? you should probably use a variable for the string length in place of the number 60. This way you can handle any length string up to the limit of your int array.