ArrayList <String> sempre produz um char [], não uma string. como posso corrigir isso?

Sebastian Mueller:

Eu quero escrever um método que usa uma string como um argumento e produz um ArrayList de strings, que são as palavras contidas na string dada. Por exemplo, a string "I ir a Marte" deve ser transformado em ArrayList [ "I", "ir", "a", "Mars"]. Aqui está o código:

    static ArrayList<String> getWords(String str){
        ArrayList<Character> charArr = new ArrayList<Character>();
        ArrayList<String> strArr = new ArrayList<String>();
        char[] chArr = str.toCharArray();
        for (Character i : chArr) {
            if (((int) i) != 32) {
                charArr.add(i);
            }
            else {
                strArr.add(charArr.toString());
                charArr.clear();
            }
        }
        if (! charArr.isEmpty()) strArr.add(charArr.toString());
        return strArr;
    }

A questão é que, em vez de ficar a matriz desejada de Cordas, recebo uma matriz de charArrays. resultado esperado:

[ "I", "ir", "a", "Mars"].

A saída real:

[[I], [G, O], [t, O], [H, A, R, S]].

Eu também não sou capaz de converter essas matrizes de caracteres em strings, o que eu tentei fazer via

String string = new String(getWords(str).get(1));

Como posso consertar isso? De preferência, no GetWords-método.

Daniel K:

Isso pode ser facilmente feito com o String.split()método:

public static List<String> getWords(String str){
    String[] strArray=str.split(" "); 
    List<String> listStr = new ArrayList<String>();
    for(String strInArray : strArray){
          listStr.add(strInArray);
    }

    return listStr;
}

Aqui está a ligação para geeksforgeeks site que explicar mais sobre o splitmétodo com exemplos.

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=314439&siteId=1
Recomendado
Clasificación