Jera Balais
Jera Balais

Reputation: 61

How to get specific word in a whole string?

I am creating and android app that randomly generates any category, I would like to get the given random category word. This is the example string

String="The category Animals that starts with a letter J";

or

String="The category Colors that starts with a letter V";

I need to get the word Animals or Colors every random String is generated

Upvotes: 0

Views: 837

Answers (4)

waders group
waders group

Reputation: 538

Use this, it might fix your issue

String string = "The category Colors that starts with a letter V";

String[] ar = string.split(" ");

System.out.println(ar[2]);

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You may use regex.

Matcher m = Pattern.compile("\\bcategory\\s+(\\S+)").matcher(str);
while(m.find()) {
   System.out.println(m.group(1));
 }

OR

Matcher m = Pattern.compile("(?<=\\bcategory\\s)\\S+").matcher(str);
while(m.find()) {
   System.out.println(m.group());
 }

Upvotes: 1

DonMushroom
DonMushroom

Reputation: 442

A not so advanced solution, but easy to understand:

    public void findCategory() {
    String string = "The category Colors that starts with a letter V";

    String[] split = string.split(" ");
    int i;

    for (i = 0; i < split.length; i++) {
        if ("category".equals(split[i])) {
            break;
        }
    }

    System.out.println(split[i + 1]);
}

Upvotes: 1

Shoeb Siddique
Shoeb Siddique

Reputation: 2825

Please use Matcher and Pattern -

 String input = "The category Animals that starts with a letter J";
            Matcher m1 = Pattern.compile("^The category (.*) that starts with a letter (.*)$").matcher(input);
            if(m1.find()) {
                String _thirdWord = m1.group(1); // Animals
                String _lastWord  = m1.group(2); // J
                System.out.println("Third word : "+_thirdWord);
                System.out.println("Last Word : "+_lastWord);

            }

Upvotes: 0

Related Questions