My situation: I have a string (called str). The length of the string must be a multiple of 30 (eg 30, 60, 90). If the length of the str is not a multiple of 30, add spaces " " to the end of it.
Something like this:
if (str.length() / 30 != ????) {
//add spaces to the end
}
Of course, the code above is not correct. It would be very appreciated if you could help me with this.
Thanks in advance!
this code is not tested but i guess it will work:
int a = str.length()%30;
for(int i=0; i<=a; i++)
str = str + " ";
You can quite simply do:
if(str.length()%30!=0)
str = String.format("%1$-"+(((str.length()/30)*30)+30)+"s", str);
str.length()%30
gives the remainder on dividing the length by 30. If it is not 0, then you have to add spaces.
String.format("%1$-"+(((str.length()/30)*30)+30)+"s", str)
adds the spaces to the right of the String.
Or even simply, you can do:
while(str.length()%30 !=0)
str+= ' ';
What would you do to check if a number is a multiple of 30 in simple Maths
?
Yes, you would divide and check if the remainder is 0 or not, right?
That's how you'll do it in Java
. To get the remainder in Java
, Modulus(%)
operator is used. So, you can do it like this :
if (str.length() % 30 != 0) {
//add spaces to the end
str += " ";
}
or if you want to add spaces to make the length a multiple of 30, then do this:
int remainder = str.length() % 30;
if (remainder != 0) {
//add spaces to the end
int numSpacesRequired = 30-remainder; //no. of spaces reuired to make the length a multiple of 30
for(int i = 0; i < numSpacesRequired; i++)
str += " ";
}
Read more about the basic operators in Java
here .
You can use Modulo
to achieve that:
if (str.length() % 30 != 0) {
//add spaces to the end
str += ' ';
}
Simply: (Tested and worked)
public static void main(String[] args) {
String str = "AYOA"; //Length is only 4
//If the remainder of the str's length is not 0 (Not a multiple)
if (str.length() % 30 != 0){
str += ' ';
}
System.out.println("[" + str + "]"); //A space is added at the back
}
If you want to add the space continuously until the length is a multiple of 30:
public static void main(String[] args) {
String str = "AYOA"; //Length is only 4
//If the remainder of the str's length is not 0 (Not a multiple)
//Repeat until is multiple of 30
while(str.length % 30 != 0){
str += ' ';
}
System.out.println("[" + str + "]"); //A space is added at the back
}
use StringBuilder to build whitespaces
String str="multiple of 30";
int spacesNum=str.length()%30; //get the remainder
StringBuilder spaces=new StringBuilder(); //build white spaces
for(int j=0;j<spacesNum;j++){
spaces.append(' ');
}
System.out.println(str+spaces.toString());
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.