[英]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.我刚开始学习 Java 并遇到了这个练习题的问题。 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:样品 output:
2 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.请试试这个 - 如果您使用的是 Java8,并且目的是计算重复的行(而不是单词),看看它是否有帮助。 This is using input from the file "error.txt" in your local anywhere.这是使用本地任何地方的文件“error.txt”的输入。
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: Output 是:
(1) times: hi.... (1) 次:嗨....
(2) times: hello.... (2) 次:你好....
You'll need to add a Java Map to memorize what input lines you've already encountered, something like您需要添加Java Map以记住您已经遇到的输入行,例如
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您可以在此处阅读有关此主题的更多信息动态编程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.