Skip to main content
gamedev.net
🔒 Locked

[java] Should be an easy question

Started by Mulligan 1 reply 300+ views
Original Post
Mulligan
Mulligan
I have the code: public void searchString( String str ) { String text = new String( textArea.getText() ); for( int a = 0; a < text.length() - str.length(); a++ ) { for( int b = 0; b < str.length(); b++ ) { if( text[a+b] != str[ b ] ) { break; } if( b == str.length() - 1 ) { System.out.println( "Found a match!!!" ); } } } } And I get the error: "Array required, but java.io.String found if( text[a+b] != str[ b ] )" I can't index a string? That seems strange if you ask me. Why can't I and how do I? [edited by - Mulligan on October 10, 2002 10:41:58 PM]
Martee
Martee
You can use the String class''s charAt() method to get the character at a given position.
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
CaptainJester
CaptainJester
First off, String is class in Java and classes cannot overload operators. So it is not like vextor in C++, where you can just index into it like an array.

So this line:

if( text[a+b] != str[ b ] )
{
break;
}

becomes(using charAt as Martee suggested):

if( text.charAt(a+b) != str.charAt( b ) )
{
break;
}


You should not do all this work, when the API does it for you. Just use:

int index=text.indexOf(str);

index will hold the starting position of str in text . It will hold -1 if str is not found.



Make it work.
Make it fast.

"I’m happy to share what I can, because I’m in it for the love of programming. The Ferraris are just gravy, honest!" --John Carmack: Forward to Graphics Programming Black Book
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.