Suppose we have a text in which the text is: Number = 1 Vasya Number = 2 Valera Number = 3 Kolya

It is necessary to translate the text into a string (this is not a problem) and find all the numbers, preferably only those that go after "Number =", and write to variables / array, not the essence, overlaid Google, did not find anything (mb I'm dumb). Help how to solve?

    2 answers 2

    You can do the following:

    1. We divide the entire line using "Number = " as a separator.
    2. In each resulting substring of the form "1 Vasya" we take the part up to the space and convert it to Integer .
    3. We put this all into an array.

    Code:

     // Наш тСкст String text = "Number = 1 Vasya Number = 2 Valera Number = 3 Kolya"; // Π”Π΅Π»ΠΈΠΌ Π΅Π³ΠΎ, ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡ Ρ€Π°Π·Π΄Π΅Π»ΠΈΡ‚Π΅Π»ΡŒ String substrings[] = text.split("Number\\s*=\\s*"); // Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΏΡƒΡΡ‚ΡƒΡŽ ΠΊΠΎΠ»Π»Π΅ΠΊΡ†ΠΈΡŽ ArrayList<Integer> arrayList = new ArrayList<>(); // ΠŸΡ€ΠΎΡ…ΠΎΠ΄ΠΈΠΌΡΡ ΠΏΠΎ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ²ΡˆΠΈΠΌΡΡ подстрокам for (int i = 1; i < substrings.length; ++i) { String str = substrings[i]; arrayList.add(new Integer(str.substring(0, str.indexOf(' ')))); } // Π’Ρ‹Π²ΠΎΠ΄ΠΈΠΌ arrayList Π½Π° экран arrayList.forEach(System.out::println); // Если Π½ΡƒΠΆΠ½ΠΎ послС ΡΠΎΠ·Π΄Π°Ρ‚ΡŒ массив ΠΏΡ€ΠΈΠΌΠΈΡ‚ΠΈΠ²ΠΎΠ²: int numbers[] = new int[arrayList.size()]; for (int i = 0; i < numbers.length; ++i) { numbers[i] = arrayList.get(i); } 

    I used "Number\\s*=\\s*" as a separator so that everything works, even if you have no spaces before the = sign or after, or there are several of them.

    Here it is:

     new Integer(str.substring(0, str.indexOf(' '))) 

    We take one of the substrings, and "rip out" a part of it from the very beginning to the first space. After we create an Integer instance using a constructor that takes a string as a parameter.

    We are going through the cycle, starting from substring 1 , since null will either be empty or contain the text preceding the Number... we Number... .

    And further. If you want to make something more universal in order to find such occurrences in different places of arbitrary text, then you need to use more complex regular expressions that you are unlikely to just take and write. So learn the theory about regulars ...

       package com.company; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { //тСкстовик File file = new File("C:\\text.txt"); //строка String s = ""; Scanner sc = new Scanner(file); while (sc.hasNext()) String s=sc.next(); //Ρ€Π°Π·Π΄Π΅Π»ΠΈΡ‚Π΅Π»ΡŒ String i = "Number = "; //массив List<String> array = new ArrayList<>(); //БобствСнно Π°Π»Π³ΠΎΡ€ΠΈΡ‚ΠΌ while (s.contains(i)) { array.add(""+s.charAt(s.indexOf(i) + i.length())); s = s.substring(s.indexOf(i)+i.length()+1); } //Π²Ρ‹Π²ΠΎΠ΄ массива System.out.println(array); } }