简体   繁体   中英

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

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); 
    }
}   


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM