troubleshooting Question

Getting correct find position for a String search in text.

Avatar of krakatoa
krakatoaFlag for United Kingdom of Great Britain and Northern Ireland asked on
Java
8 Comments1 Solution16 ViewsLast Modified:
The code finds the String that it's asked to look for within text read-in from a file.

But when trying to find the position of that String, it over-reports it by the length of the String. This may have something to do with line feeds etc ? But if it does, then how can this be put right?

I'm using a text from novel "Pride and Prejudice" at the moment, which is read in char by char. In the method that builds the proposed found String, the var 'total' should give the number of characters processed. If the String is found in the text, then it should state its position (end) based on this 'total' variable.

If the term being searched for is at the start of the text, then it does find the correct position. But if there is another occurrence of the search term later in the text, then it overreports the position.

Here's the code :


import java.io.BufferedReader ;
import java.io.File ;
import java.io.FileReader ;
import java.util.Iterator ;
import java.util.Set ;
import java.util.Map ;
import java.util.HashMap ;
import java.util.HashSet ;
import java.util.Scanner ;



class CountChars {


static StringBuilder strb = new StringBuilder();
static int total = 0;

static String SOUGHT;
     
        public static void main (String[] args){
        
        Scanner scanner = new Scanner(System.in) ;
        
        System.out.println("\n\nInput your search . . . \n") ;
               
        String fromConsole = scanner.nextLine() ;
        
        if(fromConsole.length()==0){System.exit(0);}
        
        SOUGHT = fromConsole.toString() ;
        
        try{
        
            File file = new File("C:/EE_Q_CODE/PrideAndPrejudice.txt");
            //File file = new File("C:/EE_Q_CODE/TheBible.txt");
            //File file = new File("C:/EE_Q_CODE/WarAndPeace.txt");
            //File file = new File("C:/EE_Q_CODE/Leviathan.txt");
            
            FileReader fr = new FileReader(file);
                        
            BufferedReader br = new BufferedReader(fr);      
            
            Set <Integer> chS = new HashSet<>();
            Map <Character, Integer> count = new HashMap<>();
         
            int c;
            
            while(! ((c=(fr.read()))==-1)){
            
                if(!chS.contains((int)c)){chS.add((int)c);count.put((char)c,0);}
                int i = count.get((char)c);
                if(chS.contains((int)c)){count.replace((char)c,i,i+1);}
                builder(c);
            }
               
            Iterator it = chS.iterator();
            while(it.hasNext()){System.out.print((char)(((Integer)it.next()).intValue())+" ");}
            
            System.out.println();
            System.out.println("\nTotal characters processed : "+total);
            System.out.println();
            
                /* Alternative output method. (I prefer forEach below).
                count.entrySet().stream().forEach(e -> {
                    System.out.format("key: %s, value: %d%n", e.getKey(), e.getValue());
                });
                */
                
            count.forEach((k, v) -> { System.out.format("key: %s, value: %d%n ", k, v); });
            }catch(Exception e){e.printStackTrace();} 
            
            SOUGHT = null;
            fromConsole = null;
            System.gc();
 
        }
              
        
        static void builder(int ch){
        
            int len = strb.length();
            total++;
                
                if((char)ch==SOUGHT.charAt(0)){strb.append((char)ch);return;}
                
                if(len>SOUGHT.length()-1){strb.delete(0,strb.length());return;}
                              
                if ((char)ch==SOUGHT.charAt(len)&&SOUGHT.charAt(len-1)==strb.charAt(len-1)){strb.append((char)ch);}
                else{strb.delete(0,strb.length());return;}
                if(strb.toString().equals(SOUGHT)){System.out.printf("%n\"%s\"%s%d%n",SOUGHT," <<< found at position ",total);strb.delete(0,strb.length());}
            
            
        }
        
 }

Open in new window

builder() is the method thatdoes the searching and reports the position - (and the String).
Any ideas on how to iron this out ? Thanks.
ASKER CERTIFIED SOLUTION
Log in to continue reading
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform for $9.99/mo
View membership options
Unlock 1 Answer and 8 Comments.
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
The Value of Experts Exchange in My Daily IT Life

Experts Exchange (EE) has become my company's go-to resource to get answers. I've used EE to make decisions, solve problems and even save customers. OutagesIO has been a challenging project and... Keep reading >>

Mike

Owner of Outages.IO
Phoenix, Arizona, United States
Member Since 2016
Join a full scale community that combines the best parts of other tools into one platform.
Unlock 1 Answer and 8 Comments.
View membership options
“All of life is about relationships, and EE has made a virtual community a real community. It lifts everyone's boat.”
William Peck

Member since 2004