Reputation: 43
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
Reputation: 48278
I will suggest you a combination of String.trim Method and REGEX
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
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 String
s are immutable, you need to assign temp
with the outcome of your replace
invocation.
temp = temp.replace(" "," ");
Upvotes: 2