String splitting

S

sacha_schembri

Is there a way to split a string by line breaks ?


// Placing text in jtextarea called area
area.read(new FileReader(fc.getSelectedFile()),null);
area.setEditable(false);
JOptionPane.showMessageDialog(null, "Open File Successful");
String data = area.getText();
lines = new String[10];
lines = data.split ('\n');


his didnt work
 
S

sacha_schembri

Is there a way to split a string by line breaks ?


// Placing text in jtextarea called area
area.read(new FileReader(fc.getSelectedFile()),null);
area.setEditable(false);
JOptionPane.showMessageDialog(null, "Open File Successful");
String data = area.getText();
lines = new String[10];
lines = data.split ('\n');


his didnt work


Fixed it it had to be "\\n" instead of '\n'
 
J

Jeffrey Schwab

Is there a way to split a string by line breaks ?
lines = new String[10];
lines = data.split ('\n');

You have just allocated an array of ten Strings, then immediately lost
your reference to it. Try:

String[] lines = s.split("\n");
Fixed it it had to be "\\n" instead of '\n'

Only a single backslash should be needed, i.e. "\n".

import java.io.PrintWriter;

public class Main {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out, true);
String s = "hello\nworld";
String[] lines = s.split("\n");

int lineNo = 0;
for(String line: lines) {
out.println(++lineNo + ": " + line);
}
}
}

C:\files\usenet\java>java -cp . Main
1: hello
2: world
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,268
Messages
2,571,096
Members
48,773
Latest member
Kaybee

Latest Threads

Top