[英]How to find a particular name repeated how many number of times?
I'm recieving issue with the output can anyone help me with it?我收到输出问题,有人可以帮我吗? It is a code for finding how many times a particular name has been repeated.
它是用于查找特定名称已重复多少次的代码。
package example1;
import java.util.Scanner;
public class example1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j,t,c;
String a[]=new String[10];
String b[]=new String[10];
Scanner sc=new Scanner(System.in);
for(i=0;i<10;i++)
{
a[i]=sc.nextLine();
b[i]=a[i];
}
for(i=0;i<10;i++)
{
c=0;
for(j=i+1;j<9;j++)
{
if(b[j]==b[i])
{
c++;
for(t=j;t<10;t++)
{
b[t]=b[t+1];
}
}
}
System.out.print(b[i]+" is repeated "+ c +" times ");
}
}
}
Try this.尝试这个。
String[] arr = new String[] {"a","b","c","d","a","b","c","a","b","a"};
List<String> list = Arrays.asList(arr);
Set<String> set = new HashSet<>(list);
for(String name : set)
System.out.println(name + " is repeated " + Collections.frequency(list, name) + " times");
If you want your comparison to be case insensitive, then try this.如果您希望比较不区分大小写,请尝试此操作。
String[] arr = new String[] {"A","B","c","D","a","b","c","a","b","a"};
List<String> list = new ArrayList<>(10);
for(String name : arr)
list.add(name.toLowerCase());
Set<String> set = new HashSet<>(list);
for(String name : set)
System.out.println(name + " is repeated " + Collections.frequency(list, name) + " times");
Will require more space though.不过需要更多空间。
The following code should help for determining the repetition以下代码应该有助于确定重复
public class Repetation {
public static void main(String[] args) {
String string = "Sam sam is good boy james is sams friend clyra is clyra";
int count;
string = string.toLowerCase();
String words[] = string.split(" ");
System.out.println("Duplicate words: ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
words[j] = "0";//making it 0 for future reference
}
}
if(count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}
public static int countWord(String input, String text) {
int index = input.indexOf(text);
if (index == -1 || text.isEmpty()) {
return 0;
}
int count = 0;
do {
count++;
index = input.indexOf(text, index + text.length());
} while (index > 0 && index < input.length());
return count;
}
This code will return 4
:此代码将返回
4
:
int total = countWord("abcs8abc88habcabci7h", "abc");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.