Pierre
Pierre

Reputation: 123

Retrieve only capitalised words inside a String

Let's assume we have the following string:

String string = "Hello my name Is John doe";

I would like to get only the capitalized strings from this string, in this case: Hello, Is, John.

How can I achieve that in Java?

Upvotes: 1

Views: 73

Answers (4)

ByteHamster
ByteHamster

Reputation: 4951

Use a regex and loop through all matches:

String line = "Hello my name Is John doe";
Pattern p = Pattern.compile("([A-Z]\\w+)");
Matcher m = p.matcher(line);
while (m.find()) {
    System.out.println(m.group());
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311808

You could split the string and check each part for an uppercase first letter:

String string = "Hello my name Is John doe";
List<String> result = new LinkedList<>();

for (String s : string.split(" ")) {
    if (Character.isUpperCase(s.charAt(0))) {
        result.add(s);
    }
}

Upvotes: 6

TheLostMind
TheLostMind

Reputation: 36304

Use regex with word boundary.

public static void main(String... strings) {
    String string = "Hello my name Is John doe";
    String[] arr = string.replaceAll("\\b[a-z]\\w+\\b", "").split("\\s+");
    for (String s : arr) {
        System.out.println(s);
    }
}

O/P :

Hello
Is
John

Upvotes: 3

gvlasov
gvlasov

Reputation: 20035

Split the string at space characters, then iterate over each split part and check is its first letter is capital.

public static void main(String[] args) {
    String text = "My hovercraft is Full of Eels";
    Collection<String> startingWithCapital = new ArrayList<>();
    for (String part : text.split(" ")) {
        if (Character.isUpperCase(part.charAt(0))) {
            startingWithCapital.add(part);
        }
    }
    // Just to make sure it works
    for (String part : startingWithCapital) {
        System.out.println(part);
    }
}

This outputs:

My
Full
Eels

Upvotes: 0

Related Questions