Fill a char array with a string without posting spaces

1

My goal is to create a program that counts hits by entering this keyboard, the problem is that I can not account for those that are beyond the first space, here I leave what I wrote:

public class CuentaCaracteres {

    static void toma(String cadena){
        System.out.print(cadena);
    }

    static String lectura(){
        String palabra;
        Scanner leer=new Scanner(System.in);
        return palabra=leer.next();
    }

    static char lecturaC(){
        char buscar;
        Scanner leer=new Scanner(System.in);
        return buscar=leer.next().charAt(0);
    }

    public static void main(String[] args) {
        String palabra="";
        char buscar='b';
        int coincidencia=0;

        System.out.println("Dime una palabra, te contabilizare el numero de coincidencias");
        palabra=lectura();

        char[]caracteres= palabra.replaceAll("\W ","" ).toCharArray();   

        System.out.println("elemento a buscar");
        buscar=lecturaC();
        for(int i=0; i<caracteres.length;i++){
            if(caracteres[i]==buscar) coincidencia++;
                System.out.println(caracteres[i]);
            }
            System.out.println("Hay " + coincidencia + " coincidencias en el vector");
        }    
}
    
asked by Rafael Valls 16.11.2017 в 07:03
source

1 answer

-1

The regular expression you use ("\\ W +", "") is looking for all the words followed by a space, and delete them (both the word and the space).

Perhaps, a better expression would be that you look for all types of spaces, regardless of their length, and delete them, leaving as a result a string of only characters without spaces.

For example:

char[] caracteres = leer.nextLine().replaceAll("\s+", "").toCharArray();

EDIT: As I just read in some comments, you really do not need to delete the spaces to find matches in the loop.

    
answered by 16.11.2017 / 17:22
source