简体   繁体   中英

Split by capital letters in Java

I need to split a string by capitals and preferably make subsequent words lower case;

for example

ThisIsAString becomes This is a string

Thanks

If you want a string you can do so:

String str = "ThisIsAString";
String res = "";
for(int i = 0; i < str.length(); i++) {
   Character ch = str.charAt(i);
     if(Character.isUpperCase(ch))
       res += " " + Character.toLowerCase(ch);
     else
       res += ch;
}

It looks like you want to convert camelcase into readable language. Is that the case?

If so, this solution should work for you - How do I convert CamelCase into human-readable names in Java?

If you want subsequent words lowercased, you'll have to split to handle that yourself.

public static String cpt(String cpt){
    String new_string = "";
    for (int i=0; i < cpt.length(); i++){
        char c = cpt.charAt(i);
        if(Character.isUpperCase(c)){               
            new_string = new_string + " " + Character.toLowerCase(c);
        }
        else {
            new_string = new_string + c;
        }
    }
    return new_string;
}

Total Number of Words in a Camel Case word using char casing identification

Solution: to Hacker Rank camel case problem: https://www.hackerrank.com/challenges/camelcase/problem

public static void camelCaseWordWithIndexs(String s) {


    int startIndex = 0;
    int endIndex = 0;

    for (int i = 0; i < s.length(); i++) {
        if (Character.isUpperCase(s.charAt(i)) || i == s.length() - 1) {
            startIndex = endIndex;
            endIndex = i != s.length() - 1 ? i : i + 1;
            System.out.println(s.substring(startIndex, endIndex));
        }
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM