Функция форматирования строки в Java - PullRequest
0 голосов
/ 19 октября 2019

Я пишу функцию для форматирования ввода строки. Функция состоит в том, чтобы сделать вывод текста с отступом, с ограничением на количество символов в строке. если между словами есть лишние пробелы, '';я пропускаю лишние пробелы и ставлю только один пробел ''. если слово слишком длинное и будет превышать символ в каждой строке, я вставлю пробелы до предела и начну новую строку с этим словом в новой строке.

Я не могу создать секцию заполнения кода. это часть, которая проверяет, будет ли слово превышать лимит, и начинать новую строку со слова в новой строке.

как часть требований к назначению, мне разрешено использовать только методы charAt () и length для строки

 void runApp(){
     String text = "          Knowing You Jesus        " +
                "                                         Graham Kendrick " +
                "All I once held dear,     built my life upon " +
                "All this world reveres,    and wars to own " +
                "All I once thought gain      I have counted loss " +
                "Spent and worthless now, compared         to this " +
                "Knowing you,       Jesus " +
                "Knowing you, there is          no greater thing " +
                "You're my all, you're the best " +
                "You're my joy, my righteousness " +
                "And I love you, Lord " +
                "Now my heart's desire is to know you more " +
                "To be found in you and known as yours " +
                "To possess by faith what I could not earn " +
                "All-surpassing gift of righteousness " +
                "Oh, to know the    power of your risen life " +
                "And to know You in Your sufferings " +
                "To become like you in           your death, my Lord " +
                "So with you to         live and never die " +
                "Source:  Musixmatch " +
                "Songwriters:  Tim Hughes  /  Ben Cantelon   ";

    //limit = 60
        System.out.println(" `123456789012345678901234567890123456789012345678901234567890");`
        System.out.println(leftTextFormat(text, 60));
        System.out.println();
    }


// This prints out everything left indented, but does not pad.
String leftTextFormat(String text, int limit){
    String formattedText = "";
    int charCount = 0;
    formattedText = formattedText+"[";
    for (int i=0; i<text.length(); i++){
        if (charCount%limit ==0){
            if (text.charAt(i) == ' '){
                continue;
            }else if (text.charAt(i) != ' ' ){
                formattedText = formattedText+text.charAt(i);
                charCount++;
            }
        }else if (charCount%limit != 0){
            if (text.charAt(i) == ' '){
                if (text.charAt(i-1) != ' '){
                    formattedText = formattedText+text.charAt(i);
                    charCount++;
                }else{
                    continue;
                }
            }else if (text.charAt(i) != ' '){
                formattedText = formattedText+text.charAt(i);
                charCount++;
            }
        }
        if (charCount%limit ==0 && charCount!=0){
            formattedText = formattedText+"]\n[";
        }
    }
    return formattedText;
}

Ожидаемый результат: https://drive.google.com/file/d/1uYXtSBo37sFnpwJeBGtjF0MFYNngtZXv/view?usp=sharing

что мне удалось сделать это: https://drive.google.com/file/d/102zNMe4JhaO2IUoOPCS5GSZ02Pq9aXwX/view?usp=sharing

 123456789012345678901234567890123456789012345678901234567890
[Knowing You Jesus Graham Kendrick All I once held dear, buil]
[t my life upon All this world reveres, and wars to own All I]
[once thought gain I have counted loss Spent and worthless no]
[w, compared to this Knowing you, Jesus Knowing you, there is]
[no greater thing You're my all, you're the best You're my jo]
[y, my righteousness And I love you, Lord Now my heart's desi]
[re is to know you more To be found in you and known as yours]
[To possess by faith what I could not earn All-surpassing gif]
[t of righteousness Oh, to know the power of your risen life ]
[And to know You in Your sufferings To become like you in you]
[r death, my Lord So with you to live and never die Source: M]
[usixmatch Songwriters: Tim Hughes / Ben Cantelon 

1 Ответ

3 голосов
/ 19 октября 2019

Хорошо, попытайтесь, но ваша проблема в том, что вы только добавляете символы и фактически не устанавливаете, составляют ли эти символы слова, и если эти слова, которые вы добавляете, будут превышать ваш «предел». Следовательно, вы понятия не имеете, когда слово фактически заставит вас превысить установленный вами лимит, и впоследствии вы не будете пытаться дополнить свою линию, когда вы потенциально собираетесь преодолеть этот лимит.

По сути вам необходиморабота слово в слово и строка за строкой. Каждый раз, когда вы устанавливаете слово, проверяйте, что длина этого слова плюс длина вашей текущей строки не превышает вашего предела. Если оно больше, не объединяйте его с текущей строкой, вместо этого добавьте строку до своего предела и начните новую строку.

public String formattedLine(String singleLine, int limit) {
    int padding = limit - singleLine.length();
    String pad ="";
    for(int j = 0; j < padding; j ++) {
        pad += " ";
    }
    return  "[" + singleLine + pad + "]\n";
}

public String leftTextFormat(String text, int limit) {
    String word = "";
    String singleLine = "";
    String formattedText = "";
    for(int i=0; i<text.length(); i++) {
        if (text.charAt(i) != ' ') {
            word = word + text.charAt(i);
        } else {
            if(word.length() > 0) {
                if(singleLine.length() + word.length() >= limit) {
                  formattedText = formattedText + formattedLine(singleLine, limit);
                  singleLine = "";
                }
                if(singleLine.length() == 0) {
                    singleLine = word;
                } else {
                    singleLine = singleLine + " " + word;
                }
                word = "";
            }
        }
    }
    formattedText = formattedText + formattedLine(singleLine, limit);
    return formattedText;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...