ArrayList<String> always produces a char[], not a string. how can i fix it?

Sebastian Mueller :

I want to write a method that takes a string as an argument and produces an arraylist of strings, which are the words contained in the string given. E.g. the string "I go to Mars" should be turned into the Arraylist ["I","go","to","Mars"]. Here is the code:

    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;
    }

The issue is that, instead of getting the desired Array of Strings, I get an Array of charArrays. Expected output:

["I","go","to","Mars"].

Actual output:

[[I],[g,o],[t,o],[M,a,r,s]].

I am also not able to convert these char Arrays into strings, which I tried to do via

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

How can I fix this? Preferably in the getWords-method.

Daniel K :

This can be easily done with the String.split() method:

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;
}

Here is the link to geeksforgeeks website which explain more about the split method with examples.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308060&siteId=1