?
Solved

The indexOf method for string searching

Posted on 2003-03-13
18
Medium Priority
?
302 Views
Last Modified: 2010-03-31
Hey everyone, I really need some advice on how to use the indexOf method for searching a string. I'm trying to make a search field for a database I have but I can't get this working. Thanks
deedmans
0
Comment
Question by:deedmans
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
  • 2
  • +1
18 Comments
 
LVL 1

Expert Comment

by:pronane
ID: 8129800
here is an example, its difficult enough to understand though:

public class index {
 public static void main(String args[])
 {
  String s = "aaaaaaaaaa";
  int i = 10000000;
  int n = 0;

  // method #1

  if (args.length > 0 && 
    args[0].compareTo("index") == 0) {
   while (i-- > 0)
    n = s.indexOf('x');
  }

  // method #2

  else {
   while (i-- > 0) {
    int len = s.length();
    n = -1;
    for (int j = 0; j < len; j++) {
     if (s.charAt(j) == 'x') {
      n = j;
      break;
     }
    }
   }
  }
 }
}

0
 
LVL 1

Expert Comment

by:pronane
ID: 8129832
here is a good site that explains it look under string handling:
http://www.netguide.aust.com/tutorials/javatute2/javatute2.html#anchor%205
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8129854
What exactly is the problem?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:deedmans
ID: 8129904
// Assignment 4
// By Mark Gordon
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;


//WINDOW BIT

class LLabel extends Label{
     public LLabel(String text){
          setFont(new Font("Serif",Font.PLAIN,16));
          setBackground(Color.white);
     }
}
     
class LButton extends Button{
     public LButton(String text){
     }
}


     
class Entry{
     String author, title, publisher, year;
     
     
     Entry(String a,String t, String p, String y)
     {
          author = a;
          title = t;
          publisher = p;
          year = y;
     }
}



class Library extends Frame implements ActionListener{
    LButton down, up;
    Panel pan;
    TextField txt;
    LLabel author, title, publisher, year, prompt;
    int n=0, count=0;
    final int MAXENTRY = 100;
    Entry [] details;
   
    public Library()
    {
     setLayout(new GridLayout(5,1));
     author = new LLabel("");
     add(author);
     
     title = new LLabel("");
     add(title);
     
     publisher = new LLabel("");
     add(publisher);
     
     year = new LLabel("");
     add(year);
     
     pan = new Panel(new FlowLayout());
     prompt = new LLabel("");
     prompt.setText("Label Field");
     pan.add(prompt);
     add(pan);
     
     txt = new TextField("Insert Text Here",20);
     pan.add(txt);
     add(pan);
     
     up = new LButton("");
     up.setFont(new Font("Serif",Font.ITALIC,12));
     up.setBackground(Color.blue);
     up.setLabel("Search");
     pan.add(up);
     add(pan);
     up.addActionListener(this);
     
     
    }
   
    public void getLibrary(String f)throws IOException{
         String a, t, y, p;
         BufferedReader file = new BufferedReader(new FileReader(f));
         details = new Entry[MAXENTRY];
         
         a = file.readLine();
         while(a!=null)
         {t = file.readLine();
         p = file.readLine();
         y = file.readLine();
         details[n] = new Entry(a, t, p, y);
         n++;
         count = n;
         a = file.readLine();
    }
    n = 0;
    author.setText(""+details[n].author);
    title.setText(""+details[n].title);
    publisher.setText(""+details[n].publisher);
    year.setText(""+details[n].year);
}


         public void actionPerformed(ActionEvent e){
          if(e.getSource()==up)
              {/*I NEED A METHOD: that would search the catalogue.txt and find a string matching to the string typed in my text field. */
     }
}
}
           

//SECOND NON-WINDOW BIT

public class lab67
{
   
    public static void main(String [] args)throws InterruptedException, IOException{
     
     {
         Library b;
         b = new Library();
         b.setSize(500,400);
         b.setTitle("Database Search");
         b.setVisible(true);
         b.addWindowListener
          (new WindowAdapter()
              { public void windowClosing(WindowEvent e)
               { System.exit(0);}
              });
         b.getLibrary("catalogue.txt");
     }
    }
}

Aplogies for posting so much code. Read the actionPerformed.
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8130449
ok.. if substring is not found in a string, indexOf return -1.

So:
String a = "blha blha Anton blha"
string b = "anton"

1.
if (a.indexOf(b) != -1)
   //Then string b is in string a

If you want to ignore case:

2.
if (a.toLowerCase().indexOf(b.toLowerCase()) != -1)
   //ignore case: String b is in string a


In my example, nr 1 will not run the if block but nr 2 will
0
 

Author Comment

by:deedmans
ID: 8130819
Thanks antonsiqur, but I get the following error when I compile it:

C:\My Documents\lab67.java:116: Method toLowerCase() not found in class Entry.
            if (details[n].toLowerCase().indexOf(txt.getText().toLowerCase()) != -1)
                                      ^
1 error

Process completed.


Does this mean I have to put a method up the top of my program to declare indexOf and toLowerCase?
0
 

Author Comment

by:deedmans
ID: 8130864
Thanks antonsiqur, but I get the following error when I compile it:

C:\My Documents\lab67.java:116: Method toLowerCase() not found in class Entry.
            if (details[n].toLowerCase().indexOf(txt.getText().toLowerCase()) != -1)
                                      ^
1 error

Process completed.


Does this mean I have to put a method up the top of my program to declare indexOf and toLowerCase?
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8130925
That's because Entry is not of type String. This is for comparing Strings.

-----
class Entry{
    //added public, you should implement set's and get's instaed
    public String author, title, publisher, year;
   
   
    Entry(String a,String t, String p, String y)
    {
         author = a;
         title = t;
         publisher = p;
         year = y;
    }
}
-----
 if (details[n].author.toLowerCase().indexOf(txt.getText().toLowerCase()) != -1 || details[n].title.toLowerCase().indexOf(txt.getText().toLowerCase()) != -1 && ...)
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8130929
No sorry, && should be || (in the last sentence)
0
 

Author Comment

by:deedmans
ID: 8131341
Thanks a lot dude :) It works great! Is there any other way to do it without having to do the massive or's?
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8131390
Nopes... you must implement it somewhere...
0
 

Author Comment

by:deedmans
ID: 8131469
ah ok. I've tried putting it in a for loop since there is more than one database file but unsuccessfully :/ there are 11 different outputs for author,title,publisher and year. But the for(int n=0;n<11;n++){} aint doing the trick. Any ideas?
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8131522
Please explain better
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8131544
If you need to search in multible strings:

Strings[] manyStrings = .... (or many author.title...

boolean found = false;

for (int i = 0 ; i<manyStrings.length() ; i++) {

  if (foundIn(manyStrings[i]) {
    found = true;
    break;
   }
}

if (found) {
  The string was found in some line
}

0
 

Author Comment

by:deedmans
ID: 8131552
well, n is 0, which is the 1st Entry. How would I code it to search through all 11 entries?
0
 
LVL 2

Expert Comment

by:antonsigur
ID: 8131610
by putting it in a for loop, like you just said:

boolean found = false;

for (int i = 0 ; i<manyStrings.length() ; i++) {

 if (details[i].author.toLowerCase().indexOf(txt.getText().toLowerCase()) != -1 || details[i].title.toLowerCase .... {
   found = true;
   break;
  }
}

if (found) {
 The string was found in some line
}
0
 

Author Comment

by:deedmans
ID: 8131653
Is manyStrings my details?
0
 
LVL 2

Accepted Solution

by:
antonsigur earned 300 total points
ID: 8131715
see above
yes....
But this only tells you it was found...
you must figure it out now
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month7 days, 21 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question