繁体   English   中英

Android Java检查字符串长度 - 30的倍数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM