Yash Bathia
Yash Bathia

Reputation: 43

How to replace single space to multiple space?

There are functions available for multiple spaces to single space, but I want to add more spaces where single spaces are there.

I tried this:

int rem = b - temp.length();
for(int k = 0; k < rem; k++) {
    temp.replace(" ", "  ");
}

I want to add that much space between words as predefined length of string.

Upvotes: 0

Views: 118

Answers (2)

I will suggest you a combination of String.trim Method and REGEX

EXAMPLE:

public static void main(String[] args) {
    String temp = "Is      you       see this      is    because   ";
    String replacedString = temp.trim().replaceAll(" +", " ");
    System.out.println(temp);
    System.out.println(replacedString);
}

this will correct the temp String to

Is you see this is because

Upvotes: -1

Mena
Mena

Reputation: 48404

You only need to invoke temp.replace(" "," "); once (i.e. instead of looping) to replace all single spaces with two consecutive spaces.

However, since Strings are immutable, you need to assign temp with the outcome of your replace invocation.

temp = temp.replace(" ","  ");

Upvotes: 2

Related Questions