Gopi
Gopi

Reputation: 21

How to Add spaces between a string in Java?

I have a string like

String str = "A1HighriseA22-5sty.Elev.A3Elevator(s)A4WalkupA5RowHouseA6DetachedA7Semi-DetachedA8TownHouse";

the requirement is I need to add space before and after A1, like wise i need to do it for all the A's listed in the string (like space before and after A2, A3, A4, A5, A6, A7, A8). I am not sure whether it is possible or not. If yes, can you please help me on how to do that??

Upvotes: 0

Views: 210

Answers (2)

Sumit Pathak
Sumit Pathak

Reputation: 101

    String str1 = "A1HighriseA22-5sty.Elev.A3Elevator(s)A4WalkupA5RowHouseA6DetachedA7Semi-DetachedA8TownHouse";
    String str=""; 
    for(int i=0;i<str1.length();i++){
        if(str1.charAt(i)=='A' && (str1.charAt(i+1)=='1' || str1.charAt(i+1)=='2' || str1.charAt(i+1)=='3' || 
        str1.charAt(i+1)=='4' || str1.charAt(i+1)=='5' || str1.charAt(i+1)=='6' || str1.charAt(i+1)=='7' ||
        str1.charAt(i+1)=='8' || str1.charAt(i+1)=='9')){
            str+= " "+str1.charAt(i)+""+str1.charAt(i+1)+" ";
            i++;
        }else{
            str+=""+str1.charAt(i);
        }
    }
    System.out.println(str);

Upvotes: 0

azro
azro

Reputation: 54148

You may use String.replaceAll that accepts a regex, then just a capture group and add the spaces around

String str = "A1HighriseA22-5sty.Elev.A3Elevator(s)A4WalkupA5RowHouseA6DetachedA7Semi-DetachedA8TownHouse";
String result = str.replaceAll("(A\\d)", " $1 ");

//A1HighriseA22-5sty.Elev.A3Elevator(s)A4WalkupA5RowHouseA6DetachedA7Semi-DetachedA8TownHouse
// A1 Highrise A2 2-5sty.Elev. A3 Elevator(s) A4 Walkup A5 RowHouse A6 Detached A7 Semi-Detached A8 TownHouse

If you go to more than A9, you the muldi-digit regex

str.replaceAll("(A\\d+)", " $1 ");

Upvotes: 2

Related Questions