Orsu Suni
Orsu Suni

Reputation: 131

How to insert space before capital letter for a String using JAVA?

I have a String "nameOfThe_String". Here 1st letter of the string should be capital. So I have used

String strJobname="nameOfThe_String"; strJobname=strJobname.substring(0,1).toUpperCase()+strJobname.substring(1);

Now, I need to insert the space before uppercase letters. So, I used

strJobname=strJobname.replaceAll("(.)([A-Z])", "$1 $2");

But here I need the output as "Name Of The_String". After '_' I don't need any space even S is a capital letter.

How can I do that? Please help me with this.

Upvotes: 1

Views: 4111

Answers (3)

Yash Madlani
Yash Madlani

Reputation: 36

Here's a different way which may fulfill your requirement.

public static void main(String[] args) {

    String input;
    Scanner sc = new Scanner(System.in);
    input = sc.next();
    StringBuilder text = new StringBuilder(input);
    String find = "([^_])([A-Z])";
    Pattern word = Pattern.compile(find);
    Matcher matcher = word.matcher(text);
    while(matcher.find())
        text = text.insert(matcher.end() - 1, " ");

    System.out.println(text);
}

Upvotes: 0

anubhava
anubhava

Reputation: 785246

With look-arounds you can use:

String strJobname="nameOfThe_String";
strJobname = Character.toUpperCase(strJobname.charAt(0)) +
             strJobname.substring(1).replaceAll("(?<!_)(?=[A-Z])", " ");

//=> Name Of The_String

RegEx Demo

Upvotes: 2

Kai Weber
Kai Weber

Reputation: 398

strJobname=strJobname.replaceAll("([^_])([A-Z])", "$1 $2");

The ^ character as the first character in square brackets means: Not this character. So, with the first bracket group you say: Any character that is not a _. However, note that your regex might also insert spaces between consecutive capitals.

Upvotes: 5

Related Questions