For example, I have an array:

char[] chars = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; 

and I need to divide this array into parts by a specific letter. In this example, I want to get 3 char arrays in a single MyString[] array.

 char[] chars = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; MyString myString = new MyString(chars); MyString[] arrX = myString.split('o'); 

Current implementation:

 public MyString[] split(char c) { MyString[] arr = new MyString[3]; int j = 0; int k =0; for (int i = k; i < chars.length; i++) { if (j < 3) { if (chars[i] == c) { char[] chars = new char[i - k]; MyString myString = new MyString(chars); arr[j] = myString; k = i; } } j++; } return arr; } 
  • one
    character split to include in the array or not? - Artem Konovalov

4 answers 4

I got this solution:

 public static List<char[]> split(char[] array, char delimiter) { List<char[]> result = new ArrayList<>(); int next; int prev = 0; while ((next = getSubArray(prev, array, delimiter)) != -1) { result.add(Arrays.copyOfRange(array, prev, next)); prev = next + 1; } if (prev < array.length) result.add(Arrays.copyOfRange(array, prev, array.length)); return result; } private static int getSubArray(int start, char[] array, char delimiter) { for (int i = start; i < array.length; i++) if (array[i] == delimiter) return i; return -1; } 

Use this:

 char[] array = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; char delimiter = 'o'; for (char[] part : split(array, delimiter)) System.out.println(Arrays.toString(part)); 

The output will be as follows:

[H, e, l, l]
[, W]
[r, l, d]

    When finding a given char -a in chars (as well as reaching the end of the array), you can copy the chars from the original array from the last finding index to the current one (not including the border), and then indicate the current index as the last finding index. The initial value of the last finding is -1 .

    For convenience of calculations, the code does not save the current index, but the current index plus one. For this reason, the initial value is 0 , not -1 .

    The chars are copied to the new array, from which a new MyString object is created, which is then added to the list. A list is used instead of an array, since it is not pre-calculated how many objects will be as a result. At the end of the method, this list is converted to an array.

     public MyString[] split(char c) { ArrayList<MyString> strings = new ArrayList<>(); int lastFound = 0; for (int i = 0; i <= chars.length; i++) { if (i == chars.length || chars[i] == c) { char[] stringChars = Arrays.copyOfRange(chars, lastFound, i); strings.add(new MyString(stringChars)); lastFound = i + 1; } } return strings.toArray(new MyString[strings.size()]); } 

      If I correctly understood the task, then it is necessary to do the following:

       // исходная строка char[] chars = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; MyString s = new MyString(chars); MyString[] returnStrings = s.splitToArray('o'); // сюда мы запишем ответ ... public MyString[] splitToArray(char c) { int counter = 0; // считаем все вхождения переменной c в строку for( int i = 0; i < chars.length; i++ ) { if( chars[i] == c ) { counter++; } } // если не нашли то выходим if (counter == 0) return null; MyString[] ret = new MyString[counter+1]; int k = 0; int z = k; boolean found = false; for (int i = 0; i < counter+1; i++) { // теперь находим первое вхождение символа for(int j = k; j < chars.length; j++) { if( chars[i] == c ) { k = j; found = true; break; } } if (!found) k = chars.length; // создаем массив символов и перекидываем в него часть до интересующей нас буквы char[] charArr = new char[kz]; System.arraycopy(chars, z, charArr, 0, kz); ret[i] = new MyString(charArr); z = k; found = false; k++; } return ret; } 

      Naturally, if the indexOf method was implemented, the code would be more compact. Unfortunately, the code to check there is no possibility. Waiting for your reply comments.

      • The cycle in which elements from charse are thrown into charArr can be replaced with the line: Arrays.arraycopy (chars, z, charArr, 0, k); - Kirill Malyshev
      • @KirillMalyshev surrenders to me that we are talking about System.arraycopy . - Regent
      • Oh, right, thank you! - Kirill Malyshev
      • Thank you for reminding System.arraycopy about System.arraycopy - GreenTheGreen

      Solution using strings:

       char[] chars = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; String str = new String(chars); String[] result = str.split("o"); char[][] resultInCharArray = new char[result.length][chars.length]; for (int i = 0; i < resultInCharArray.length; i++) { resultInCharArray[i] = result[i].toCharArray(); }