如何使用for循环和方法格式化字符串

时间:2019-04-16 14:59:00

标签: java

例如,我有以下字符串:" Java is fun "

我需要格式化它,新的String必须是:"Java is fun"

我希望这很清楚。

我知道我可以使用.trim()格式化一点,但是我不会。我想尽可能地使用for循环等来修复该字符串。

public static void main(String[] args) {

String string = "   Java   is   fun  ";

}

public static void correction(String string) {
    /*I dont have any code for now but I have something in my head,
    that is I might think that can be fixed to check if first index is whitespace(blank)
    and last index is whitespace, and for other unnecessary whitespaces I think that I
    can check what is after every word. So, I think that I can go throught a whole string lenght
    and after all words I need to check how many whitespaces are there
    */

}

}

3 个答案:

答案 0 :(得分:2)

听起来像是Java的初学者课程,而一位老师提出了一个问题,该问题永远都不会适用:)就像那个曾经让我们对数组列表进行气泡排序并且我使用List与一个比较器,在11秒内完成,他让我再做一次...:)

任何人,也许可以帮忙。

public static String correction(String error) {
    String corrected = "";
    String[] tokens = error.split(" ");
    for (int i = 0; i < tokens.length; i++){
        if (tokens[i].isBlank()) {
            // do nothing / skip
        } else {
            // contains a word, so we concatenate it to the return value;
            corrected = corrected.concat(tokens[i]);

            // if we are not at the last word, add a space
            if (i < tokens.length-1) {
                corrected = corrected.concat(" ");
            }
        }
    }
    return corrected;
}

public static void main(String[] args) {
    System.out.println(correction("Java     is fun... as I am obligated to say    or  risk the   wrath of   the    Oracle    Ninjas™"));
}

输出:

run:
Java is fun... as I am obligated to say or risk the Oracle Ninjas™
    BUILD SUCCESSFUL (total time: 0 seconds)

答案 1 :(得分:-1)

根据您要在此处施加的实际规则,可以使用“”作为分隔符在输入字符串上调用String“ split”方法。这将导致字符串中的单词组成一个数组,而忽略空格,然后可以使用所需的空格数来重构String。

答案 2 :(得分:-1)

您可以按以下说明使用String.split():How to split a string in Java

您可以按照以下说明使用正则表达式:How to extract a substring using regex

您可以使用StringTokenizer,但不建议使用splitToken()。