extracting substring by lines
I am fairly new to programming so please bear with me. Say I have a large string such as this.
String story = "This is the first line.\开发者_如何学Pythonn"
+ "This is the second line.\n" + "This is the third line\n" + "This is the fourth line.\n" + "This is the fifth line.";
How would I go about extracting the first, fourth, and so on lines?
If you want to avoid creating arrays, you can use Scanner
Scanner scanner = new Scanner(story);
while(scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
String[] lines = story.split(System.getProperty("line.separator"));
String firstLine = lines[0];
// and so on
You can split on \n
, but thus you are fixed to the line separator of *nix systems. If it happens that you have to parse on windows, splitting on \n
won't work (unless of course your string is hard-coded, which defeats the whole purpose of splitting - you know which are the lines beforehand)
You can split your string into lines using the split method and then index to get the line you want:
String story =
"This is the first line.\n" +
"This is the second line.\n" +
"This is the third line\n" +
"This is the fourth line.\n" +
"This is the fifth line.";
String[] lines = story.split("\n");
String secondLine = lines[1];
System.out.println(secondLine);
Result:
This is the second line.
Notes:
- In Java indexing arrays starts at zero, not one. So the first line is
lines[0]
. - The split method takes a regular expressions as its argument.
String[] lines = story.split('\n');
String line_1 = lines[0];
String line_4 = lines[3];
or something along those lines
If the string is going to be very long, you can use a combination of a BufferedReader and a StringReader to do it one line at a time:
String story = ...;
BufferedReader reader = new BufferedReader(new StringReader(story));
while ((str = reader.readLine()) != null) {
if (str.length() > 0) System.out.println(str);
}
Otherwise, split the string into an Array, if it's small enough using Split
:
String[] lines = story.split("\n");
You would split the string into an array and then select the array elements you want
String[] arr = story.split("\n")
arr[0] // first line
arr[3] // fourth line
精彩评论