- Добавление символа новой строки в строку в Java
- Дальнейшее чтение:
- Проверка пустых или пустых строк в Java
- Проверьте, содержит ли строка подстроку
- 2. Добавление новой строки в строку
- 2.1. Использование разрывов строк CRLF
- 2.2. Использование платформо-независимых разрывов строк
- 3. Добавление новой строки в HTML
- 3.1. HTML Break Tag
- 3.2. Новая строка символов
- 3.3. Символы юникода
- 4. Заключение
- Prefer System.lineSeparator() for Writing System-Dependent Line Separator Strings in Java
Добавление символа новой строки в строку в Java
Форматирование строк и генерация вывода текста часто возникают во время программирования. Во многих случаях необходимо добавить новую строку в строку для форматирования вывода.
Давайте обсудим, как использовать символы новой строки.
Дальнейшее чтение:
Проверка пустых или пустых строк в Java
Проверьте несколько простых способов проверить, является ли строка пустой или пустой в Java.
Проверьте, содержит ли строка подстроку
Изучите различные способы поиска подстроки в строке с помощью тестов производительности
2. Добавление новой строки в строку
Операционные системы имеют специальные символы для обозначения начала новой строки. Например,in Linux, a new line is denoted by “ ”, также называетсяLine Feed. In Windows, a new line is denoted using “ ”, иногда называемыйCarriage Return песокLine Feed илиCRLF.
Добавить новую строку в Java так же просто, как добавить « ” или« ” или «\r ” в конце нашей строки».
2.1. Использование разрывов строк CRLF
Для этого примера мы хотим создать абзац, используя две строки текста. В частности, мы хотим, чтобыline2 отображался в новой строке послеline1.
Для ОС на базе Unix / Linux / New Mac мы можем использовать « ”:
String line1 = "Humpty Dumpty sat on a wall."; String line2 = "Humpty Dumpty had a great fall."; String rhyme = line1 + "\n" + line2;
Если мы работаем в ОС на базе Windows, мы можем использовать « ”:
Для ОС на базе старого Mac мы можем использовать « ”:
Мы показали три метода добавления новой строки, но жаль, что это будет зависеть от платформы.
2.2. Использование платформо-независимых разрывов строк
Мы также можем использовать системные константы, когда хотим, чтобы наш код не зависел от платформы.
Например, используяSystem.lineSeparator() для разделения строк:
rhyme = line1 + System.lineSeparator() + line2;
Или мы могли бы также использоватьSystem.getProperty(“line.separator”):
rhyme = line1 + System.getProperty("line.separator") + line2;
3. Добавление новой строки в HTML
Предположим, мы создаем строку, которая является частью HTML-страницы. In that case, we can add an HTML break tag .с
We can also use Unicode characters “& #13;” (Carriage Return) and “& #10;” (Line Feed). Хотя эти символы работают, они работают не так, как мы могли бы ожидать, на всех платформах. Вместо этого лучше использовать для разрывов строк.
Мы также можем использовать“ ” в некоторых элементах HTML, чтобы разбить строку.
Всего существует три способа разрыва строки в HTML. Мы можем решить использовать один из них, в зависимости от используемого нами HTML-тега.
3.1. HTML Break Tag
Мы можем использовать HTML-тег разрыва для разрыва строки:
Тег для разрыва строки работает почти во всех элементах HTML, таких как , , и т. Д. Однако обратите внимание, что это не работает в теге .
3.2. Новая строка символов
Мы можем использовать‘ ‘ для разрыва строки, если текст заключен в теги или :
3.3. Символы юникода
Мы можем использовать символы Юникода“& #13;” (возврат каретки) и“& #10;” (перевод строки), чтобы разбить строку. Например, в теге мы можем использовать любое из них:
rhyme = line1 + " " + line2; rhyme = line1 + "" + line2;
Для тега будут работать обе строки ниже:
rhyme = line1 + " " + line2; rhyme = line1 + " " + line2;
4. Заключение
В этой статье мы обсудили, как добавить символ новой строки в строку в Java.
Мы также увидели, как писать платформенно-независимый код для новой строки, используяSystem.lineSeparator() иSystem.getProperty(“line.separator”).
И наконец, мы закончили с тем, как добавить новую строку в случае, если мы генерируем HTML-страницу.
Полную реализацию этого руководства можно найти вover on GitHub.
Prefer System.lineSeparator() for Writing System-Dependent Line Separator Strings in Java
Join the DZone community and get the full member experience.
JDK 7 introduced a new method on the java.lang.System class called lineSeparator(). This method does not expect any arguments and returns a String that represents «the system-dependent line separator string.» The Javadoc documentation for this method also states that System.lineSeparator() «always returns the same value — the initial value of the system property line.separator .» It further explains, «On UNIX systems, it returns » \n «; on Microsoft Windows systems it returns » \r\n «.»
Given that a Java developer has long been able to use System.getProperty(«line.separator») to get this system-dependent line separator value, why would that same Java developer now favor using System.lineSeparator instead? JDK-8198645 [«Use System.lineSeparator() instead of getProperty(«line.separator»)»] provides a couple reasons for favoring System.lineSeparator() over the System.getProperty(String) approach in its «Description»:
A number of classes in the base module use System.getProperty(«line.separator») and could use the more efficient System.lineSeparator() to simplify the code and improve performance.
As the «Description» in JDK-8198645 states, use of System.lineSeparator() is simpler to use and more efficient than System.getProperty(«line.separator») . A recent message on the core-libs-dev mailing list provides more details and Roger Riggs writes in that message that System.lineSeparator() «uses the line separator from System instead of looking it up in the properties each time.»
The performance benefit of using System.lineSeparator() over using System.getProperty(«line.separator») is probably not all that significant in many cases. However, given its simplicity, there’s no reason not to gain a performance benefit (even if tiny and difficult to measure in many cases) while writing simpler code. One of the drawbacks to the System.getProperty(String) approach is that one has to ensure that the exactly matching property name is provided to that method. With String -based APIs, there’s always a risk of spelling the string wrong (I have seen «separator» misspelled numerous times as «seperator»), using the wrong case, or accidentally introducing other typos that prevent exact matches from being made.
The JDK issue that introduced this feature to JDK 7, JDK-6900043 («Add method to return line.separator property»), also spells out some benefits in its «Description»: «Querying the line.separator value is a common occurrence in large systems. Doing this properly is verbose and involves possible security failures; having a method return this value would be beneficial.» Duplicate JDK-6264243 («File.lineSeparator() to retrieve value of commonly used ‘line.separator’ system property») spells out advantages of this approach with even more detail and lists «correctness», «performance», and «ease of use and cross-platform development» as high-level advantages. Another duplicate issue, JDK-6529790 («Please add LINE_SEPARATOR constant into System or some other class»), makes the point that there should be a «constant» added to «some standard Java class, as String or System,» in a manner similar to that provided for file separators by File.pathSeparator.
One of the messages associated with the JDK 7 introduction of System.lineSeparator() justifies it additions with this description:
Lots of classes need to use System.getProperty(«line.separator») . Many don’t do it right because you need to use a doPrivileged block whenever you read a system property. Yet it is no secret — you can divine the line separator even if you have no trust with the security manager.
An interesting side note related to the addition of System.lineSeparator() in JDK 7 is that the Javadoc at that time did not indicate that the method was new to JDK 7. JDK-7082231 («Put a @since 1.7 on System.lineSeparator») addressed this in JDK 8 and two other JDK issues (JDK-8011796 and JDK-7094275) indicate that this was desired by multiple Java developers.
The introduction of System.lineSeparator() was a very small enhancement, but it does improve the safety and readability of a relatively commonly used API while not reducing (and, in fact, while improving) performance.
Published at DZone with permission of Dustin Marx , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.