1

I have the following texts:

"The data of Branch 1 are correct - true"
"data of Branch 4 are correct - false"

For each text, I would like to get the number of branch and the boolean value either true or false. The outcome for each line will be:

1 true
4 false

How can I do that?

Adam Amin
  • 1,406
  • 2
  • 11
  • 23

3 Answers3

3

You can do it in different manner.

One of the simplest in this case is split the string and getting the fifth and ninth element

String sentence = "The data of Branch 1 are correct - true"; 
String[] elements = string.split(" "); then get relevant elements of array.
// elements[4]   is the string 1 (you can convert it to int if necessary with Integer.parseInt(elements[4]) )
// elements[8]   is the string true (you can convert it to boolean if necessary with Boolean.parseBoolean(elements[4]) )

Other possibilities are:

  • Using regular expressions (find the number and search the words true false)
  • Using the position (you know that the number starts always in the same position and that the boolean value is always at the end)

Knowing that you can create a method similar to the following to print the relevant parts:

public static void printRelevant(String string) {
    String[] elements = string.split(" "); 
    System.out.println(elements[4] + " " + elements[8]);
}

...

pritnRelevant("The data of Branch 1 are correct - true");
printRelevant("The data of Branch 4 are correct - false");

Thanks to the comments of Sotirios I saw that the 2 phrases are not equals. So it is necessary to use a regular expression to extract the relevant parts:

public static void printRelevant(String string) {
    Pattern numberPattern = Pattern.compile("[0-9]+");
    Pattern booleanPattern = Pattern.compile("true|false");

    Matcher numberMatcher = numberPattern.matcher(string);
    Matcher booleanMatcher = booleanPattern.matcher(string);
    if (numberMatcher.find() && booleanMatcher.find()) {
        return numberMatcher.group(0) + " " + booleanMatcher.group(0);
    }
    throw new IllegalArgumentException("String not valid");
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

Step 1: Use String splitting by space to put all elements in an array

Step 2: Find the indexes of the elements you're interested in

Step 3: Parse each element String into the required type (Integer and Boolean)

That should get you started!

Tiberiu
  • 990
  • 2
  • 18
  • 36
0

If you always have the same "pattern" of the input string, you can simply do:


input = "The data of Branch 1 are correct - true";

// split by space
String [] words = input.split(" ");

// take the values (data) that you need.
System.out.println(words[4] + " " + words[8]);
// also you can cast values to the needed types

Something like this. Best way, probably, will be to use Regex to take needed data from the input string.

Eugene
  • 301
  • 2
  • 12