Results 1 to 4 of 4

Thread: searching

  1. #1
    nalinda is offline Member
    Join Date
    Nov 2007
    Posts
    7
    Rep Power
    0

    Default searching

    given a sequence of letters, and an array that has a random sequence of letters in each element, how do i find if any of the elements match the given sequence, and which element number it is at?
    i.e:given "abcdefg" , String [] array = {bfg, fgj, cde, efg, ght} , how do i say that cde and efg are inside that sequence?

  2. #2
    staykovmarin is offline Senior Member
    Join Date
    Nov 2007
    Location
    Newport, WA
    Posts
    141
    Rep Power
    0

    Default

    You can always use a regex. If you dont know what a regex is, i strongly suggest you read Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes)
    Java Code:
                    // all the patterns that are going to have to be matched
    		String [] array = {"bfg", "fgj", "cde", "efg", "ght"}; 
    		Matcher m;
    		// scans trough each pattern
    		for(int i = 0; i < array.length; i++) {
                            // creates a new pattern for each element in the array
    			Pattern p = Pattern.compile(array[i]);
                            // attepts to match the created pattern to the specified string
    			m = p.matcher("abcdefg");
                            // if the pattern matches: print
    			if (m.find())
    				System.out.println(array[i] + " is contained");
    		}

  3. #3
    nalinda is offline Member
    Join Date
    Nov 2007
    Posts
    7
    Rep Power
    0

    Default

    i see what u mean...but how would i do it using indexOf?

  4. #4
    staykovmarin is offline Senior Member
    Join Date
    Nov 2007
    Location
    Newport, WA
    Posts
    141
    Rep Power
    0

    Default

    Here is a simpler way, although less powerful, it might be better suited for whatever you are doing.
    Java Code:
    		String [] array = {"bfg", "fgj", "cde", "efg", "ght"}; 
    		String toTest = "abcdefg";
    		for(int i = 0; i < array.length; i++) {
    			if (toTest.contains(array[i])) 
    				System.out.println(array[i] + " is contained");
    		}

Similar Threads

  1. Searching XML file using DOM
    By simon in forum XML
    Replies: 5
    Last Post: 03-30-2009, 02:27 AM
  2. Searching an arraylist
    By adelgado0723 in forum New To Java
    Replies: 1
    Last Post: 04-15-2008, 02:09 PM
  3. Replies: 0
    Last Post: 04-14-2008, 09:39 PM
  4. recursively searching through arraylists
    By newtojava7 in forum New To Java
    Replies: 1
    Last Post: 03-17-2008, 03:36 AM
  5. searching within a JList
    By newtojava7 in forum New To Java
    Replies: 1
    Last Post: 03-10-2008, 01:12 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •