AJBM Posted December 27, 2012 at 10:40 PM Report #488729 Posted December 27, 2012 at 10:40 PM Boas! Eu tenho que fazer um programa que conte quantas palavras se repetem numa string, por exemplo: String teste="Olá Bom Bom dia" O resultado devia ser algo do tipo: Olá Bom dia teste 1 2 1 Eu tenho isto, eu sei que não esta correcto será que me podiam dar umas orientações, private String teste = "Olá Bom Bom dia"; public void MontarMatriz() { String[] contem; int count = 0; int[] countArray = new int[4]; contem = teste.split(" "); for (int i = 0; i < contem.length; i++) { for (int j = 0; j < contem.length; j++) { if (contem[i].equals(contem[j])) { count++; } } countArray[i] = count; } System.out.println("Ola :" + countArray[0]); } }
HappyHippyHippo Posted December 27, 2012 at 11:14 PM Report #488741 Posted December 27, 2012 at 11:14 PM não comentado porque acho o código demasiado directo e simples de perceber Map<String, Integer> countWords(String str) { HashMap<String, Integer> result = new HashMap<String, Integer>(); String[] words = str.split(); for(int i = 0; i < words.length; i++) { if (result.containsKey(words[i])) result.get(words[i])++; else result.put(words[i], 1); } return result; } ps : não testado IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
AJBM Posted December 28, 2012 at 10:26 PM Author Report #488878 Posted December 28, 2012 at 10:26 PM Boas! O método que tu disponibilizas te esta a funcionar. Se eu utilizar uma string qualquer ela funciona mas se utilizar a string que criei no main, não funciona, eu ainda não descobri porque. @Override public String eliminarDigitos(String string) { char[] tmp = new char[string.length()]; String car = ""; for (int i = 0, j = 0; i < tmp.length; i++) { if (!(Character.isDigit(string.charAt(i)))) { tmp[j] = string.charAt(i); j++; } } for (int i = 0; i < tmp.length; i++) { car += tmp[i]; } string = car; return string; } @Override public String eliminarCar(String string) { string = string.replaceAll("[.?!/;,:]", ""); return string; } public Map<String, Integer> countWords(String str) { HashMap<String, Integer> result = new HashMap<String, Integer>(); String[] words; words = str.toLowerCase().split(" "); for (int i = 0; i < words.length; i++) { if (result.containsKey(words[i])) { result.put(words[i], result.get(words[i]) + 1); } else { result.put(words[i], 1); } } return result; } public static void main(String[] args) { MotorBusca motBusca = new MotorBusca(); String string = "12Bo2m dia d123ia ?BOm"; System.out.println("String a testar: " + string); string = motBusca.eliminarDigitos(string); System.out.println("Elimina numeros: " + string); string = motBusca.eliminarCar(string); System.out.println("Eliminar pontuacao: " + string); System.out.println(""+ motBusca.countWords("Bom dia dia BOm"));//funciona System.out.println(""+ motBusca.countWords(string));//nao funciona }
HappyHippyHippo Posted December 28, 2012 at 10:48 PM Report #488883 Posted December 28, 2012 at 10:48 PM porque dizes que não funciona ? qual o output (todo) da aplicação ? IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
AJBM Posted December 28, 2012 at 10:59 PM Author Report #488886 Posted December 28, 2012 at 10:59 PM String a testar: 12Bo2m dia d123ia ?BOm Elimina numeros: Bom dia dia ?BOm Eliminar pontuacao: Bom dia dia BOm CONTAR: {bom=1, bom =1, dia=2}
HappyHippyHippo Posted December 28, 2012 at 11:06 PM Report #488888 Posted December 28, 2012 at 11:06 PM adiciona uns trim's Map<String, Integer> countWords(String str) { HashMap<String, Integer> result = new HashMap<String, Integer>(); String[] words = str.trim().split(); for(int i = 0; i < words.length; i++) { String word = words[i].trim(); if (result.containsKey(word)) result.get(word)++; else result.put(word, 1); } return result; } IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
AJBM Posted December 28, 2012 at 11:08 PM Author Report #488891 Posted December 28, 2012 at 11:08 PM funcionou obrigado 👍
AJBM Posted December 29, 2012 at 05:02 PM Author Report #488935 Posted December 29, 2012 at 05:02 PM Boas! É possível ir buscar apenas o valor da palavra ou seja, Bom=1 eu queira só o 1, eu fiz isto, mas o ultimo numero não está aparecer public void MontarMatriz() { Map result = countWords(teste); List <Integer> inte= new ArrayList<Integer>(); inte.addAll(result.values()); for (int i = 0; i < inte.size(); i++) { System.out.println(""+inte.get(i)); } } public static void main(String[] args) { MotorBusca motBusca = new MotorBusca(); String string = "12Bo2m dia d123ia ?BOm O.;lá ,opção"; System.out.println("String a testar: " + string); string = motBusca.eliminarDigitos(string); System.out.println("Elimina numeros: " + string); string = motBusca.eliminarCar(string); System.out.println("Eliminar pontuacao: " + string); System.out.println("CONTAR: "+ motBusca.countWords(string)); System.out.println("Matriz: "); motBusca.MontarMatriz(); } String a testar: 12Bo2m dia d123ia ?BOm O.;lá ,opção Elimina numeros: Bom dia dia ?BOm O.;lá ,opção Eliminar pontuacao: Bom dia dia BOm Olá opção CONTAR: {bom=2, olá=1, opção=1, dia=2} Matriz: 2 1 1
HappyHippyHippo Posted December 29, 2012 at 05:23 PM Report #488936 Posted December 29, 2012 at 05:23 PM (edited) primeiro de tudo, tens de começar a indentar o código como deve de ser !!! public void MontarMatriz() { Map result = countWords(teste); List <Integer> inte= new ArrayList<Integer>(); inte.addAll(result.values()); for (int i = 0; i < inte.size(); i++) { System.out.println(""+inte.get(i)); } } de que buraco negro tiraste a variável teste, dada como argumento à função countWords ?? o modelo normal de iteração de elementos de uma Collection public void MontarMatriz(String string) { Iterator<Integer> iter = countWords(string).iterator(); while (iter.hasNext()) System.out.println(iter.next()); } Edited December 29, 2012 at 05:23 PM by HappyHippyHippo IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
AJBM Posted December 31, 2012 at 12:17 PM Author Report #489122 Posted December 31, 2012 at 12:17 PM (edited) a variável teste esta definida na classe. Eu estou agora com outro problema eu tenho que guardar os resultados numa matriz, tenho 2 strings por exemplo string1="Ola Bom Bom dia" string2 ="Ola boa Noite", podes dar me uma dica para fazer algo deste género Ola Bom dia boa Noite string1 1 2 1 0 0 string2 1 0 0 1 1 ,eu acho que vou ter de ter um vector com as palavras todas,e outro com o nome das strings Edited December 31, 2012 at 12:18 PM by AJBM
HappyHippyHippo Posted December 31, 2012 at 02:42 PM Report #489141 Posted December 31, 2012 at 02:42 PM não, o mais simples é usares novamente o HashMap IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now