[英]Android Java Check Length of String - Multiple of 30
我的情況:我有一個字符串(稱為str)。 字符串的長度必須是30的倍數(例如30,60,90)。 如果str的長度不是30的倍數,則在其末尾添加空格“”。
像這樣的東西:
if (str.length() / 30 != ????) {
//add spaces to the end
}
當然,上面的代碼不正確。 如果你能幫助我,我將非常感激。
提前致謝!
這段代碼沒有經過測試,但我想它會起作用:
int a = str.length()%30;
for(int i=0; i<=a; i++)
str = str + " ";
你可以很簡單地做:
if(str.length()%30!=0)
str = String.format("%1$-"+(((str.length()/30)*30)+30)+"s", str);
str.length()%30
給出了將長度除以str.length()%30
的余數。如果它不是0,則必須添加空格。
String.format("%1$-"+(((str.length()/30)*30)+30)+"s", str)
將空格添加到String的右側。
或者甚至簡單地說,你可以這樣做:
while(str.length()%30 !=0)
str+= ' ';
如果簡單Maths
的數字是30的倍數,你會怎么做?
是的,你會分開並檢查余數是否為0,對吧?
這就是你用Java
做的。 為了獲得Java
的余數,使用了Modulus(%)
運算符。 所以,你可以這樣做:
if (str.length() % 30 != 0) {
//add spaces to the end
str += " ";
}
或者如果要添加空格以使長度為30的倍數,請執行以下操作:
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 += " ";
}
在此處閱讀有關Java
基本運算符的更多信息。
您可以使用Modulo
來實現:
if (str.length() % 30 != 0) {
//add spaces to the end
str += ' ';
}
簡單地說:(經過測試和工作)
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
}
如果要連續添加空格,直到長度為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
}
使用StringBuilder來構建空格
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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.