[英]How can I compare a string with smaller and smaller parts of another string?
[英]How do i split an input string into a smaller string and compare them
我剛開始學習 Java 並遇到了這個練習題的問題。 我應該在輸入中打印重復行的數量。 任何幫助,將不勝感激!
樣本輸入:
測試
測試
測試
樣品 output:
2
這是我沒有成功的嘗試:
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);
}
}
請試試這個 - 如果您使用的是 Java8,並且目的是計算重復的行(而不是單詞),看看它是否有幫助。 這是使用本地任何地方的文件“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()))));
}
我的文件輸入為
你好
你好
你好
Output 是:
(1) 次:嗨....
(2) 次:你好....
您需要添加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);
}
}
您可以在此處閱讀有關此主題的更多信息動態編程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.