Java 17 Recipes


-7. Breaking String Lines


Download 3.2 Mb.
Pdf ko'rish
bet55/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   51   52   53   54   55   56   57   58   ...   245
Bog'liq
Java 17 Recipes

3-7. Breaking String Lines
 Problem
You want to break the string into lines.
 Solution
Use the java.lang.String.lines() method that allows the division in lines, as shown 
in Listing 
3-2
.
Listing 3-2. Using the lines Method
import java.util.stream.Stream;
class LineTerminators {
public static void main(String[] args) {
String nameString = "Luciano \nManelli \nTaranto";
Stream stringStream = nameString.lines();
stringStream.forEach(System.out::println);
}
}
It returns the following output.
Luciano
Manelli
Taranto
Chapter 3 StringS


89
 How It Works
A new method was included in the String class in Java 11. It read contents of files 
processing each line separately and returns a stream of lines extracted from the string 
based on line terminators, such as a line feed character (\n), a carriage return character 
(\r), or a carriage return immediately followed by a line feed (\r\n).
3-8. Repeating Strings
 Problem
You want to repeat strings.
 Solution
Use the java.lang.String.repeat(int) method as follows.
String nameString = "luciano";
String repeatString = nameString.repeat(3);
It returns the following output.
lucianolucianoluciano
 How It Works
Java 11 introduced the repeat method, which returns the concatenation of a string 
repeated as many times as provided by the int (count) parameter.
3-9. Changing the Case of a String
 Problem
A portion of your application contains case-sensitive string values. You want to change 
all the strings to uppercase or lowercase before they are processed to avoid any case 
sensitivity issues down the road.
Chapter 3 StringS


90

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   51   52   53   54   55   56   57   58   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling