Remove word from char array that starts and ends with 'a' in java

-1

I have the following string

String cadena="la amiga es mia";

I pass it to an array of chars:

char[]caracteres=cadena.toCharArray

Now what I want to do is from that array get the words that start and end with 'a' in this case you have to leave

palabras que empiezan y acaban por 'a':amiga

How do I do it?

    
asked by david sierra fernandez 01.03.2018 в 13:35
source

2 answers

3

First we pass the string to an array.
Then we go through the array and check the first and last letter of each word.
If both are "a" we eliminate it and add it to the ArrayList of eliminated words.
Then we paint the original phrase without the words removed and below the words we just deleted

String texto = "La cadena es amiga mia";
String [] array = texto.split(" ");
ArrayList eliminadas = new ArrayList<String>();

for(int i = 0; i<array.length; i++){
        if(array[i].charAt(0) == 'a' && array[i].charAt(array[i].length()-1) == 'a'){
            eliminadas.add(array[i]);
            array[i] = "";
        }

    }
    System.out.println( Arrays.toString(array).replace(",","") + "\n Palabras eliminadas : ");
    for(int j = 0; j<eliminadas.size(); j++){
        System.out.print(eliminadas.get(j) + ", ");
    }

If you notice, when you paint the phrase of the words deleted, where was the word "friend" now there are two spaces, the solution to that you look for it: P

    
answered by 01.03.2018 в 14:07
3

I recommend using split to separate the word. and then verify if the first and last character are a.

Make sure you have lowercase or uppercase letters (I chose lowercase letters), then create a ArrayList to save all the words that start and end with a

Also add that if the word comes with accents, similarly look for them. Look for matches with Amiga (without accent) but show the result with Amigá

String string = "la Amigá es mía azula";
String palabraLimpia = new String(string);
palabraLimpia = Normalizer.normalize(palabraLimpia, Normalizer.Form.NFD);
palabraLimpia = palabraLimpia.replaceAll("[^\p{ASCII}]", "");
System.out.println(palabraLimpia);
ArrayList<String> lista = new ArrayList<String>();
String[] parts = string.split(" ");
String[] parts2 = palabraLimpia.split(" ");
for (int i = 0; i < parts2.length; i++) {
    char[]caracteres = parts2[i].toCharArray();
    int largo = caracteres.length;
    if (Character.toUpperCase(caracteres[0]) == 'A' && Character.toUpperCase(caracteres[largo-1]) == 'A') {
        lista.add(parts[i]);
    }
}
for (String palabra: lista) {
    System.out.println(palabra);
}
    
answered by 01.03.2018 в 13:58