Shop OBEX P1 Docs P2 Docs Learn Events
bug in java.lang.String class — Parallax Forums

bug in java.lang.String class

Peter VerkaikPeter Verkaik Posts: 3,956
edited 2004-12-04 13:13 in General Discussion
I discovered a bug in the java.lang.String class.
Method public int indexOf(String str) returns
the index of str in this string.

Simple program


static String s1 = new String("ABCABCD");
static String s2 = new String("ABCD");

static void main() {
· int c = s1.indexOf(s2); //find "ABCD" in "ABCABCD" so c should be 3
· System.out.println(c);· //shows -1 -> s2 not found in s1
}

Here is the listing of indexOf and the solution

· /**
·· * Finds the first occurance of the specified String in this String.
·· *
·· * @param str the String to search for.
·· * @return the index of the first character matching the String or -1 if the
·· *·· String is not found.
·· */
· public int indexOf(String str) {
··· int start = -1;
··· int count = 0;
··· for ( int i = 0; i < length; i++ ) {
····· if ( str.value[noparse][[/noparse]count] == value[noparse][[/noparse]i] ) {
······· if ( start == -1 ) {
········· start = i;
······· }
······· count++;
······· if ( count == str.length ) {
········· return start;
······· }
····· }
····· else {
······· count = 0;
······· if (start >= 0) i = start+1;· // I added this line, in case of a mismatch
············································ //the seach must restart one pos after start
······· start = -1;
····· }
··· }
··· return -1;
· }

Please update your String.java file.

regards peter
Sign In or Register to comment.