Scanner sc = new Scanner(System.in).useDelimiter(","); String s = sc.nextLine().trim(); int k =1; for(int i=0; i < s.length(); i++) { if(s.charAt(i) == ',') { k++; } } String[] arr = new String[k]; 

found the length of the desired array, but can not fill it

    1 answer 1

    Please do not split . Now you say that without StringTokenizer

     Scanner scanner = new Scanner(System.in); StringTokenizer st = new StringTokenizer(scanner.nextLine()); String[] stringArray = new String[st.countTokens()]; int k = 0; while(st.hasMoreTokens()){ stringArray[k++] = st.nextToken(); } 

    PS If your teacher wants you to do everything with your hands - split only for whitespace or punctuation is implemented trivially.

    UPD

    Separator:

     Scanner scanner = new Scanner(System.in); StringTokenizer st = new StringTokenizer(scanner.nextLine(), ","); String[] stringArray = new String[st.countTokens()]; int k = 0; while(st.hasMoreTokens()){ stringArray[k++] = st.nextToken(); } Stream.of(stringArray).forEach(System.out::println); 

    Input:

    This, is, a, test

    Output:

    This

    is

    a

    test

    • if we have a string (This, is, a, test), then this method does not immediately insert the entire string into the first element of the array? - Sergo Ghazaryan
    • The StringTokenizer has a delimeter parameter where you can specify any delimiter or string from delimiters. By default, if the delimiter is not specified, the string from " \t\n\r\f" Updated the answer. - iksuy
    • Thanks for this !!! - Sergo Ghazaryan