Java에서 텍스트 정렬

Sheeraz Gul 2023년10월12일
Java에서 텍스트 정렬

텍스트를 정렬하기 위해 Java.text.Format 클래스를 확장하는 클래스를 만들 수 있습니다. 이 자습서는 Java에서 텍스트를 정렬하는 방법을 보여줍니다.

Java에서 텍스트 정렬

Format은 숫자, 메시지, 날짜 등과 같은 민감한 정보의 형식을 지정하는 추상 기본 클래스입니다. Text_Alignment라는 클래스를 구현하여 Format 클래스를 확장하여 정렬하도록 텍스트 형식을 지정할 수 있습니다.

이 클래스는 Center, RightLeft의 세 가지 열거형을 정의하며 나중에 switch 조건에서 주어진 지침에 따라 텍스트를 정렬하는 경우로 사용됩니다. 이 클래스는 한 줄에 최대 문자 수를 사용한 다음 각 줄을 정렬합니다.

예를 참조하십시오.

package delftstack;

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class Text_Alignment extends Format {
  private static final long serialVersionUID = 1L;

  public enum Align_Text {
    LEFT,
    CENTER,
    RIGHT,
  }

  // justification for formatting
  private Align_Text Current_Alignment;

  // maximum length of a line
  private int Maximum_Chars;

  public Text_Alignment(int Maximum_Chars, Align_Text alignment) {
    switch (alignment) {
      case LEFT:
      case CENTER:
      case RIGHT:
        this.Current_Alignment = alignment;
        break;
      default:
        throw new IllegalArgumentException("invalid justification");
    }
    if (Maximum_Chars < 0) {
      throw new IllegalArgumentException("Maximum_Chars should be positive.");
    }
    this.Maximum_Chars = Maximum_Chars;
  }

  public StringBuffer format(
      Object Input_Object, StringBuffer Align_Position, FieldPosition Ignore_Position) {
    String Demo = Input_Object.toString();
    List<String> Strings_List = Split_String(Demo);
    ListIterator<String> List_Iterator = Strings_List.listIterator();

    while (List_Iterator.hasNext()) {
      String Wanted_String = List_Iterator.next();

      // put the spaces in the right place.
      switch (Current_Alignment) {
        case RIGHT:
          ALIGN(Align_Position, Maximum_Chars - Wanted_String.length());
          Align_Position.append(Wanted_String);
          break;

        case CENTER:
          int toAdd = Maximum_Chars - Wanted_String.length();
          ALIGN(Align_Position, toAdd / 2);
          Align_Position.append(Wanted_String);
          ALIGN(Align_Position, toAdd - toAdd / 2);
          break;

        case LEFT:
          Align_Position.append(Wanted_String);
          ALIGN(Align_Position, Maximum_Chars - Wanted_String.length());
          break;
      }
      Align_Position.append("\n");
    }
    return Align_Position;
  }

  protected final void ALIGN(StringBuffer Append_To, int Length) {
    for (int i = 0; i < Length; i++) Append_To.append(' ');
  }

  String format(String Demo) {
    return format(Demo, new StringBuffer(), null).toString();
  }

  // ParseObject will be required but it is not useful here.
  public Object parseObject(String Source_String, ParsePosition position) {
    return Source_String;
  }

  private List<String> Split_String(String Demo) {
    List<String> List = new ArrayList<String>();
    if (Demo == null)
      return List;
    for (int x = 0; x < Demo.length(); x = x + Maximum_Chars) {
      int End_Index = Math.min(x + Maximum_Chars, Demo.length());
      List.add(Demo.substring(x, End_Index));
    }
    return List;
  }

  public static void main(String[] args) {
    String Demo_Text =
        "DelftStack is a resource for everyone interested in programming, embedded software, and electronics."
        + "It covers the programming languages like Python, C/C++, C#, and so on in this website's first development stage."
        + "Open-source hardware also falls in the website's scope, like Arduino, Raspberry Pi, and BeagleBone."
        + "DelftStack aims to provide tutorials, how-to's, and cheat sheets to different levels of developers and hobbyists.";
    // Align Left
    Text_Alignment align = new Text_Alignment(50, Align_Text.LEFT);
    System.out.println("This is the left alignment of the given text: ");
    System.out.println(align.format(Demo_Text));

    // Align Right
    Text_Alignment align1 = new Text_Alignment(50, Align_Text.RIGHT);
    System.out.println("This is the right alignment of the given text: ");
    System.out.println(align1.format(Demo_Text));

    // Align Center
    Text_Alignment align2 = new Text_Alignment(50, Align_Text.CENTER);
    System.out.println("This is the center alignment of the given text: ");
    System.out.println(align2.format(Demo_Text));
  }
}

위의 코드는 주어진 텍스트를 Left, RightCenter 정렬 형식으로 지정합니다. 출력 참조:

This is the left alignment of the given text:
DelftStack is a resource for everyone interested i
n programming, embedded software, and electronics.
It covers the programming languages like Python, C
/C++, C#, and so on in this website's first develo
pment stage.Open-source hardware also falls in the
 website's scope, like Arduino, Raspberry Pi, and
BeagleBone.DelftStack aims to provide tutorials, h
ow-to's, and cheat sheets to different levels of d
evelopers and hobbyists.

This is the right alignment of the given text:
DelftStack is a resource for everyone interested i
n programming, embedded software, and electronics.
It covers the programming languages like Python, C
/C++, C#, and so on in this website's first develo
pment stage.Open-source hardware also falls in the
 website's scope, like Arduino, Raspberry Pi, and
BeagleBone.DelftStack aims to provide tutorials, h
ow-to's, and cheat sheets to different levels of d
                          evelopers and hobbyists.

This is the center alignment of the given text:
DelftStack is a resource for everyone interested i
n programming, embedded software, and electronics.
It covers the programming languages like Python, C
/C++, C#, and so on in this website's first develo
pment stage.Open-source hardware also falls in the
 website's scope, like Arduino, Raspberry Pi, and
BeagleBone.DelftStack aims to provide tutorials, h
ow-to's, and cheat sheets to different levels of d
             evelopers and hobbyists.
작가: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook