IT박스

자바 문자열 줄 바꿈

itboxs 2020. 7. 13. 21:43
반응형

자바 문자열 줄 바꿈


나는 같은 문자열을 가지고있다.

"I am a boy".

이런 식으로 인쇄하고 싶습니다

"I 
am 
a
boy".

아무도 나를 도울 수 있습니까?


System.out.println("I\nam\na\nboy");

System.out.println("I am a boy".replaceAll("\\s+","\n"));

System.out.println("I am a boy".replaceAll("\\s+",System.getProperty("line.separator"))); // portable way

당신은 또한 사용할 수 있습니다 System.lineSeparator():

String x = "Hello," + System.lineSeparator() + "there";

System.out.printf("I %n am %n a %n boy");

산출

I 
 am 
 a 
 boy

설명

%n대신 OS 독립적 인 개행 문자 로 사용 하는 것이 좋고 사용 하는 \n것보다 쉽습니다.System.lineSeparator()

사용하는 %n이유는 각 OS에서 새 줄이 다른 문자 집합을 나타 내기 때문입니다.

Unix and modern Mac's   :   LF     (\n)
Windows                 :   CR LF  (\r\n)
Older Macintosh Systems :   CR     (\r)

LF줄 바꿈 의 약어 이고 CR캐리지 리턴 의 약어입니다 . 이스케이프 문자는 괄호 안에 표시됩니다. 따라서 각 OS에서 새 줄은 시스템에 특정한 것을 나타냅니다. %nOS에 구애받지 않고 이식 가능합니다. 그것은 의미 \n유닉스 시스템 또는 \r\nWindows 시스템과에 이렇게. 따라서 사용하지 말고 \n대신 사용하십시오 %n.


여러 가지 방법으로 수행 할 수 있습니다. 나는 두 가지 간단한 방법을 언급하고 있습니다.

  1. 아래와 같이 매우 간단한 방법 :

    System.out.println("I\nam\na\nboy");
    
  2. 다음과 같이 연결하여 수행 할 수도 있습니다.

    System.out.println("I" + '\n' + "am" + '\n' + "a" + '\n' + "boy");
    

시험:

System.out.println("I\nam\na\nboy");

코드를 모든 시스템에서 이식 가능하게 만들려면 다음을 사용하십시오.

public static String newline = System.getProperty("line.separator");

Windows마다 "\ r \ n"을 사용하고 Classic Mac은 "\ r"을 사용하고 Mac과 Linux는 모두 "\ n"을 사용하므로 OS마다 다른 줄 바꿈 표기법이 사용되므로 중요합니다.

Commentors - please correct me if I'm wrong on this...


\n is used for making separate line;

Example:

System.out.print("I" +'\n'+ "am" +'\n'+ "boy"); 

Result:

I
am
boy

If you simply want to print a newline in the console you can use ´\n´ for newlines.

If you want to break text in swing components you can use html:

String s = "<html>first line<br />second line</html>";

If you want to have your code os-unspecific you should use println for each word

System.out.println("I");
System.out.println("am");
System.out.println("a");
System.out.println("boy");

because Windows uses "\r\n" as newline and unixoid systems use just "\n"

println always uses the correct one


What about %n using a formatter like String.format()?:

String s = String.format("I%nam%na%nboy");

As this answer says, its available from java 1.5 and is another way to System.getProperty("line.separator") or System.lineSeparator() and, like this two, is OS independent.


Full program example, with a fun twist:

Open a new blank document and save it as %yourJavaDirectory%/iAmABoy/iAmABoy.java. "iAmABoy" is the class name.

Paste the following code in and read through it. Remember, I'm a beginner, so I appreciate all feedback!

//The class name should be the same as your Java-file and directory name.
class iAmABoy {

    //Create a variable number of String-type arguments, "strs"; this is a useful line of code worth memorizing.
    public static void nlSeparated(String... strs) {

        //Each argument is an str that is printed.
        for (String str : strs) {

            System.out.println(str);

        }

    }

    public static void main(String[] args) {

        //This loop uses 'args' .  'Args' can be accessed at runtime.  The method declaration (above) uses 'str', but the method instances (as seen below) can take variables of any name in the place of 'str'.
        for (String arg : args) {

            nlSeparated(arg);

        }

        //This is a signature.  ^^
        System.out.print("\nThanks, Wolfpack08!");
    } 

}

Now, in terminal/cmd, browse to %yourJavaDirectory%/iAmABoy and type:

javac iAmABoy.java
java iAmABoy I am a boy

You can replace the args I am a boy with anything!


Go for a split.

String string = "I am a boy";
for (String part : string.split(" ")) {
    System.out.println(part);
}

System.out.println("I\nam\na\nboy");

This works It will give one space character also along before enter character


I use this code String result = args[0].replace("\\n", "\n");

public class HelloWorld {

    public static void main(String[] args) {
        String result = args[0].replace("\\n", "\n");
        System.out.println(result);
    }
}

with terminal I can use arg I\\nam\\na\\boy to make System.out.println print out

I
am
a
boy

enter image description here


you can use <br> tag in your string for show in html pages

참고URL : https://stackoverflow.com/questions/7833689/java-string-new-line

반응형