使字符串的特定部分在控制台输出中显示为彩色

Make specific parts of a string appear colored in console output

我正在尝试使输入文本文件中包含大写字母的所有字符串在输出控制台中显示为绿色。例如,输入文本文件包含 "I'm used to speak in English." 输出应该是输入文本文件 "I'm used to speak in English." 中的整个句子,字符串 "I'm" 和 "English" 显示为绿色。但我只设法以绿色显示字符串 "I'm" 和 "English",而没有在控制台上显示整个句子。

谁能帮忙解决这个问题?我的代码:

    public static void main(String[] args) throws FileNotFoundException {

    Scanner sc = new Scanner(new File("Testing.txt"));

    while(sc.hasNext()){
        String line = sc.nextLine();
        String arr [] = line.split(" ");

        StringBuilder out = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if (Character.isUpperCase(arr[i].charAt(0))) {
                out.append(arr[i]);
            }
        }

        if (out.length() > 1) {
            out.setLength(out.length() -2);
        }

        System.out.println ("\u001B[32m " + out);
    }
} 

尝试这样的事情:

public static void main(String[] args) throws FileNotFoundException {
    Scanner sc = new Scanner(new File("Testing.txt"));

    while(sc.hasNext()){
        String line = sc.nextLine();
        String arr [] = line.split(" ");

        StringBuilder out = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if (Character.isUpperCase(arr[i].charAt(0))) {
                out.append("\u001B[32m").append(arr[i]).append(" ");
            } else {
                out.append("\u001b[0m").append(arr[i]).append(" ");
            }
        }

        System.out.println (out);
    }
}

想法是不仅存储第一个大写字母的单词,而且存储所有单词,并使用 \u001b[0m 转义序列来重置其他单词的格式。

当您使用 ANSI 颜色着色时,您应该在完成字符串的着色部分后重置颜色,否则整个字符串将具有相同的颜色。

以下示例使用 colorizeString 方法将绿色设置为传递的 String,然后重置颜色(序列 "\u001B[0m"):

public static void main(final String[] args) throws FileNotFoundException {

     Scanner sc = new Scanner(new File("Testing.txt"));


    while (sc.hasNext()) {
        String line = sc.nextLine();
        String arr[] = line.split(" ");

        StringBuilder out = new StringBuilder();
        for (String element : arr) {
            if (Character.isUpperCase(element.charAt(0))) {
                colorizeString(out, element);
            }
            else{
                out.append(element);
            }

            // add the previously removed space
            out.append(" ");
        }

        System.out.println(out);
    }
}

private static void colorizeString(final StringBuilder builder, final String str) {

    builder.append("\u001B[32m");// GREEN foreground
    builder.append(str);
    builder.append("\u001B[0m");// Reset colors

}

另请阅读 Roma Khomyshyn 提到的主题: How to print color in console using System.out.println?