如何编写for循环来添加空白( java 语)

x7rlezfr  于 2021-07-08  发布在  Java
关注(0)|答案(4)|浏览(531)

我必须为这段代码做一个for循环,并想知道如何在每边添加空格。

//3. The method returns a String that contains width characters and centres the
// text within the width by adding sufficient spaces before and after the text.
//If the total number of spaces required to centre the text(i.e the total of spaces before and after)
//is an odd number the additional space should be on the left of the text. If the text is longer/wider
//the method should return only the leftmost characters of the text(i.e. it should trim text text).
public static String centre(String text, int width){

    int padding = width - text.length() / 2;

    if(padding == 0)

这就是我目前所拥有的

bxjv4tth

bxjv4tth1#

试试这个

public static String centre(String text, int width) {
        // Calculate the max padding length for left padding.
        int overrall_padding = width - text.length();
        int padlen = (overrall_padding >> 1) + (width & 1);
        // Create the padding as character array.
        char[] padding = new char[padlen];
        // Fill the array with spaces
        for(int i=0;i<padding.length;i++)padding[i]=' ';
        // Create a builder.
        StringBuilder builder = new StringBuilder();
        // Append the at the begining as left padding.
        builder.append(padding);
        // append the text
        builder.append(text);
        // append the right padding. (note: the reuse of padding, division of width by 2)
        builder.append(padding, 0, overrall_padding >> 1);
        // Return
        return builder.toString();

    }

注意重复使用 char[] 缓冲区只是为了在保持效率的同时优化速度。

fv2wmkja

fv2wmkja2#

你可以这样做。此方法使用 StringBuilder 包含文本。不需要检查文本何时与宽度匹配,因为如果出现这种情况,循环将不会接合。单引号环绕文本以显示间距。

String text = "no spaces needed";
System.out.printf("'%s'%n", centre(text,text.length()));
text = "even on both sides";
System.out.printf("'%s'%n", centre(text,text.length()+10));
text = "extra space on left";      
System.out.printf("'%s'%n", centre(text,text.length()+11));
text = "this text is too long";      
System.out.printf("'%s'%n", centre(text,text.length()-5));

印刷品

'no spaces needed'
'     even on both sides     '
'      extra space on left     '
'this text is too'

public static String centre(String text, int width){
    int len = text.length();
    // automatically adjusts for odd number of spaces on left and even on right
    int left = (width-len+1)/2;
    int right = width-len-left;

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < left; i++) {
        sb.append(' ');
    }
    sb.append(text);
    for (int i = 0; i < right; i++) {
        sb.append(' ');
    }
    // return the string or a right trimmed string if the string exceeds the width.
    return sb.substring(0,width);
}
knpiaxh1

knpiaxh13#

可以附加到 StringBuilder 在循环中:

public static String centre(String text, int width) {
    int diff = width - text.length();
    if (diff <= 0) {
        // nothing needs to be done
        return text;
    }
    // right side is rounded down
    int paddingRight = diff / 2;
    // left side gets the remainder
    int paddingLeft = diff - paddingRight;
    // start building the string
    StringBuilder builder;
    // add the left padding
    for (int i = 0; i < paddingLeft; i ++) {
        builder.append(' ');
    }
    // add the actual text
    builder.append(text);
    // add the right padding
    for (int i = 0; i < paddingRight; i ++) {
        builder.append(' ');
    }
    // get a string from the builder
    return builder.toString();
}
ffx8fchx

ffx8fchx4#

你也会发现这很有趣。我已经应用了string.format()来生成填充。str.substring()用于trim()
语法:

String.format("%[L]s", str);

例子

String.format("%3s", ""); // Generates 3 spaces
String.format("%5s", ""); // Generates 5 spaces
String.format("%3s%s%3s", "", "Hello", ""); //***Hello***; *=space

参考文献:https://www.geeksforgeeks.org/how-to-pad-a-string-in-java/
代码:

class Solution{
    public static String centre(String text, int width){
        int length = text.length();
        if(length >= width)
            return text.substring(0, width);        // trimming to width
        else{
            int padding = width - length;
            if(padding == 1)
                return String.format(" %s", text);  // adding single space to the left
            else{
                int padLeft, padRight;
                padLeft = padRight = padding >> 1;  // dividing by 2
                if((padding & 1) == 1)              // if odd number the adding extra 1 to left
                    padLeft += 1;
                return String.format("%" + padLeft + "s%s%" + padRight + "s", "", text, "");
            }            
        }
    }

    public static void main(String[] args){
        System.out.println(centre("Hello", 4));
        System.out.println(centre("Hello", 5));
        System.out.println(centre("Hello", 6));
        System.out.println(centre("Hello", 7));
        System.out.println(centre("Hello", 8));
    }
}

输出(*用于可视化空间):

Hell Hello

* Hello
* Hello*
**Hello*

相关问题