How do i split an input string into a smaller string and compare them

Viewed 40

I just started picking up Java and ran into a problem with this practice question. I am supposed to print the number of duplicated lines in an input. Any help would be appreciated!

Sample input:
test
test
TesT

Sample output:
2

Here is my attempt that did not work:


public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int count=0;
        while(scan.hasNext()) {
            String s = scan.nextLine()+"\n";
            String first=s.split("\n")[0];
            for (int i=0;i<s.length();i++){
                if(first==s.split("\n")[i])
                    count++;
            }
        }
        System.out.println(count); 
    }
}   


2 Answers

Please try this - if you are using Java8, and the intent is to count duplicate lines(not words) and see if it helps. This is using input from the file "error.txt" in your local anywhere.

public static void main(String args[]) throws IOException {
            Map<String, Long> dupes = Files.lines(Paths.get("/Users/hdalmia/Documents/error.txt"))
                    .collect(Collectors.groupingBy(Function.identity(),
                            Collectors.counting()));

        
            dupes.forEach((k, v)-> System.out.printf("(%d) times : %s ....%n",
                    v, k.substring(0,  Math.min(50, k.length()))));
        }

My File had input as

hello

hello

hi

Output was :

(1) times : hi ....

(2) times : hello ....

You'll need to add a Java Map to memorize what input lines you've already encountered, something like

public class Solution {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Map map=new HashMap();  
    int count=0;
    while(scan.hasNext()) {
        String s = scan.nextLine()+"\n";
        if(map.hasKey(s)) count++;
        else map.put(s, true);
    }
    System.out.println(count); 
  }
}   

You can read more about this topic here dynamic-programming

Related