Java12String.indent()

Java12String.indent() 首页 / Java入门教程 / Java12String.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个字符的文件。

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

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

教程推荐

大模型应用开发实战 -〔黄佳〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

零基础GPT应用入门课 -〔林健(键盘)〕

Vim 实用技巧必知必会 -〔吴咏炜〕

性能测试实战30讲 -〔高楼〕

黄勇的OKR实战笔记 -〔黄勇〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

玩转Spring全家桶 -〔丁雪丰〕

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