-2

I have to deal with Strings like: "hasCityName" , "hasAddress", "hasNumberOfStreet".

What I need is to extract the words from those Strings, so if we have: "hasNumberOfStreet", I would like to get: "has", "Number" , "Of" and "Street".

Is there any function for this? or I should go through the string checking when the char changes to uppercase/lowercase and so on?

Thanks in advance.

Antman
  • 453
  • 2
  • 8
  • 18

3 Answers3

4

You can use regex (?=[A-Z])

str.split("(?=[A-Z])");
  1. [A-Z] indicates splitting from a capital letter
  2. ?= is a positive lookahead that is required to keep the delimiter.

Code

String str = "hasNumberOfStreet";
String spStr[] = str.split("(?=[A-Z])");

for(String s : spStr) System.out.println(s);

Output

has
Number
Of
Street
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • Here you are not taking into account "has", right?. Useful anyway, thank you! – Antman May 10 '17 at 07:26
  • @AntonioSerrano `has` is the first string and it will automatically get splitted from first delimiter. There's no need to handle it . – Raman Sahasi May 10 '17 at 07:27
0

Trying using the below regex for splitting the string

<<your string>>.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")
mhasan
  • 3,703
  • 1
  • 18
  • 37
0

Approach with regex is good but if you need to do it without regex in a simple way you can use Character.getType(charAt) == Character.UPPERCASE_LETTER check to find index of uppercase letter and extract preceding word:

public static void main(String[] args) {
        // String in = "hasNumberOfStreetD";
        String in = "hasNumberOfStreet";
        ArrayList<String> words = new ArrayList<>();
        int lastUpperCaseIndex = 0;
        for (int i = 0; i < in.length(); i++) {
            char charAt = in.charAt(i);
            if (Character.getType(charAt) == Character.UPPERCASE_LETTER) {
                words.add(in.substring(lastUpperCaseIndex, i));
                lastUpperCaseIndex = i;
            }
        }
        if (lastUpperCaseIndex < in.length()) {
            words.add(in.substring(lastUpperCaseIndex, in.length()));
        }
        words.forEach(System.out::println);
    }

Prints:

has
Number
Of
Street
Jay Smith
  • 2,331
  • 3
  • 16
  • 27