Java12 - String.indent()

Java12 - String.indent() 首页 / Java入门教程 / Java12 - String.indent()

学习使用 String.indent() API在Java中缩进(左缩进)字符串。此API已在 Java 12 中引入。

String.indent(count)API

此方法根据count的值调整给定字符串的每一行的缩进,并标准化行终止符。

/**
* count - number of leading white space characters to add or remove
* returns - string with indentation adjusted and line endings normalized
*/
public String indent​(int count)

请注意, count string>的值可以是正数或负数。

  • positive number – If count > 0 然后在每行的开头插入空格。
  • negative number – If count < 0 然后在每行的开头删除空格。
  • negative number – If count > available white spaces 然后删除所有前导空格。

每个空格字符都被视为一个字符。特别是,制表符" \ t"被视为单个字符;它不会扩展。

无涯教程网

String.indent​() 示例

Java程序将白色字符串转换成缩进8个字符的文件。

链接:https://www.learnfk.comhttps://www.learnfk.com/java/java12-string-left-indent-lines.html

来源:LearnFk无涯教程网

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;
 
public class Main
{
    public static void main(String[] args)
    {
        try
        {
            Path file = Files.createTempFile("testOne", ".txt");
 
            //Write strings to file indented to 8 leading spaces
            Files.writeString(file, "ABC".indent(8), StandardOpenOption.APPEND);
            Files.writeString(file, "123".indent(8), StandardOpenOption.APPEND);
            Files.writeString(file, "XYZ".indent(8), StandardOpenOption.APPEND);   
 
            //Verify the content
            Stream<String> lines = Files.lines(file);
 
            lines.forEach(System.out::println);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

程序输出。

ABC
123
XYZ

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

软件测试52讲 -〔茹炳晟〕

Java业务开发常见错误100例 -〔朱晔〕

爆款文案修炼手册 -〔乐剑峰〕

攻克视频技术 -〔李江〕

Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕

去无方向的信 -〔小麥〕

网络排查案例课 -〔杨胜辉〕

李智慧 · 高并发架构实战课 -〔李智慧〕

手把手带你写一个 MiniTomcat -〔郭屹〕

好记忆不如烂笔头。留下您的足迹吧 :)