I am learning Java not so long ago, and I want to create a simple replacement library. And I can not exactly understand what method to use with this. I need the numbers to be replaced by text, while the cycle is working. And the number of values ​​was determined by the length of the array, or what would replace it. I attach the code, the code does not handle the replacement, it simply displays the numbers.

int i1=0; String [] numbers = new String[3]; numbers[0]="1"; numbers[1]="2"; numbers[2]="3"; String[] symbols = new String[3]; symbols[0]="одИн"; symbols[1]="двА"; symbols[2]="Тры"; int LengthArray = numbers.length; do { i1=i1+1; // i1++ //System.out.println(i1); String i01 = Integer.toString(i1); System.out.println(i01.replaceAll(numbers[i1],symbols[i1])); } while(i1<=LengthArray - 1); 

    2 answers 2

    I didn’t quite understand what exactly you want to do, but if you got the idea right, you’d better use the associative container map.

     Map<Character, String> replaces = new HashMap<>(); replaces.put('1', "один"); replaces.put('2', "два"); /* ... */ for (Character c : input) System.out.println(replaces.get(c)); 
    • Oh, thank you gotta try. I repeat, of course, I need the numbers to be replaced by text, while the cycle is working. The number of values ​​was determined by the length of the array, or what would replace it. - VladDimir

    In general, the answer from @saltukkos fully satisfies your condition. As input, there comes a Map, where the correspondence of a digit to a symbol is clearly indicated:

     public static void main(String[] args) { //Мапа для замены значений Map<String, String> replaces = new HashMap<>(); replaces.put("1", "один"); replaces.put("2", "два"); replaces.put("3", "три"); //Исходная строка String s = "1,2,3,4,5 ааа рпрмим"; //Переводим исходную строку в массив символов char[] chars = s.toCharArray(); //Буфер числа. Сюда будем добавлять поочередно цифры, пока не кончится число StringBuilder buffer = new StringBuilder(); //Проходим по массиву исходных символов for (int i=0; i<chars.length;i++) { //Если символ = цифра if (Character.isDigit(chars[i])) { //Добавляем цифру в буфер buffer.append(chars[i]); } else { //Если в буфере есть другие цифры if (buffer.length()>0) { //Пытаемся получить из мапы значение, соотв. нашему числу //Если такое число есть, мапа передаст в переменную его словестный аналог, иначе null String word = replaces.get(buffer.toString()); //Если мы что-то получили из мапы if (word != null) //Заменяем в исходной строке число из буфера на слово s = s.replaceAll(buffer.toString(), word); //Заново инициализируем буфер buffer = new StringBuilder(); } } } } 

    HashMap stores data in Key-value format. At the same time, a search by key takes a constant, fairly short time (there is really the worst case when linear, but here it is not so important).