SPLIT with \n Delimiter - java

I need to split string with delimiter of \n when I use this code:
String delimiter = "\n";
String[] temp;
temp = description2[position].split(delimiter);
for (int i = 0; i < temp.length; i++) {
holder.weeklyparty_text3.setSingleLine(false);
holder.weeklyparty_text3.setText(temp[i]);
}
but not get split string from \n.

You need to escape the backslash in the delimiter string: "\\n"

Split uses regex - so to split on a newline, you should use:
String delimiter = "\\n";

In order to support Unix and Windows new lines use:
String lines[] = String.split("\r?\n");
as described in:
Split Java String by New Line

Related

Convert ArrayList<String> With Quotes Read from an external txt file to ArrayList<String> Without the Quotes Using Java 8

I am trying to read huge lines of words in quotes e.g "DSRD","KJHT","BFXXX","OUYTP" from a text file, so that I can have something like [DSRD, KJHT, BFXXX, OUYTP].
I have tried these 2 codes below but still returns the lines with quotes:
1. List<String> lines = Files.readAllLines(Paths.get(filePath), ENCODING);
2. List<String> lines = new ArrayList<>(Files.readAllLines(Paths.get(filePath)));
Is there a way I can make this return just the list of the Strings without the quotes in each of the Strings?
Any help would be greatly appreciated.
Thanks
You can remove the quotes after reading the file using String#replaceAll :
List<String> lines = Files.readAllLines(Paths.get(filePath), ENCODING);
lines = lines.stream().map(s -> s.replaceAll("\"", "")).collect(Collectors.toList());
You can split the words as they are separated by commas and apply transformation on them and finally join them back:
for(int i = 0; i < lines.size(); i++) {
String line = lines[i];
String[] words = line.split(",");
for (int j = 0; j < words.length; j++) {
words[j] = words[j].replaceAll("^\"|\"$", "");
}
lines[i] = String.join(",", words);
}

Converting newline character in char array to string?

char[] charArray = {'\n'};
String str = String.valueOf(charArray);
System.out.println(str);
So I want to obtain a string of the newline character that is in the array.
However, with this code, the output is simply a blank space. How can I get
String str= "\n" ?
'\n' is the encoding for a newline character. Perhaps you want:
String str = "\\n"
or perhaps you want
char[] charArray = {'\\','n'};
String str = String.valueOf(charArray)

replacing \n in a String

There are several answers to similar questions as mine, but I have tried several of them and they are not working. I must be doing something stupid.
I have
String newline = System.getProperty("line.separator");
String content = "Test\n another line\n";
if(content.contains("\\n")) {
content = content.replaceAll("(\\n)", newline);
System.out.print(content);
}
I also tried "\n" and "\\n" in the regex. The content remains unchanged using replaceAll.
Okay facts:
\r is a CR, U+000D
\n is a LF, U+000A
Those characters you can put in a String
String s = "line 1.\nline 2.\n";
String newline = System.getProperty("line.separator");
newline can be "\n" (1 char) or "\r\n" (2 chars) or still something else.
If you would read this text, reading first a backslash and then an n, it would be in code:
String nl = "\\n"; // Two chars, an escaped backslash and a `n`.
String nl = "\\" + 'n'; // Two chars, an escaped backslash and a `n`.
If you would want to replace these two chars with a real newline:
s = s.replace("\\n", "\n");
s = s.replace("\\n", newline); // Platform dependent
Now java regex is still more complex, as it escapes regex letters with a backslash, which in Strings is escaped itself:
You will not need a regex replaceAll/replaceFirst here, but it would go as:
s = s.replaceAll("\\\\n", "\n");
The pattern containing two backslashes: regex escaping of one backslash.
String newline = System.getProperty("line.separator");
String content = "Test\\n another line\\n";
if(content.contains("\\n")) {
content = content.replaceAll("\\\\n", newline);
System.out.print(content);
}
The extra 2 slashes are the escape characters
I also tried this and it works
content.replace("\\n", "\\r\\n")
but
content.replaceAll("\\n", "\\r\\n")
does not.
So in the end I used
while(content.contains("\\n")) {
content = content.replace("\\n", newline);
}
And this solves my problem, not elegant, but it works.

Split command on a nextElement

I am making a java servlet and am trying to make it display a preview of 3 different articles. I want it to preview the first sentence of each article, but can't seem to get split to work properly since I am reading the articles in with tokenizer. So I have something like:
while ((s = br.readLine()) != null) {
out.println("<tr>");
StringTokenizer s2 = new StringTokenizer(s, "|");
while (s2.hasMoreElements()) {
if (index == 0) {
out.println("<td class='first'>" + s2.nextElement() + "</td>");
}
out.println("</tr>");
}
index = 0;
}
How do I make s2.nextElement print out only the first sentence instead of the whole article? I imagine I could do split with a delimiter of ".", but can't get the code to work right. Thanks.
Try
s2.nextElement().split("\\.")[0];
to get the first sentence in the paragraph.
It would be better to use a Scanner:
Scanner scanner = new Scanner(new File("articles.txt"));
while (scanner.hasNext()) {
String article = scanner.next();
String[] parts = article.split("\\s*\\|\\s*");
String title = parts[0];
String text = parts[1];
String date = parts[2];
String image = parts[3];
String firstSentence = text.replaceAll("\\..*", ".");
// Output what you like about the article using the extracted parts
}
Scanner.next() reads in the whole line (the default delimiter is the newline char(s)).
split("\\s*\\|\\s*") splits the line on pipe chars (which have to be escaped because the pipe char has special regex meaning) and the \s* consumes any whitespace that may surround the pipe chars.
What I did was change hasMoreElements() to hasMoreTokens(). I then found the first occurrence of a ".". and created an int value. I then printed out a substring. here is what my code looked like:
while((s = br.readLine()) != null){
out.println("<tr>");
StringTokenizer s2 = new StringTokenizer(s, "|");
while (s2.hasMoreTokens()){
if (index == 0){
String one = s2.nextToken();
int i = one.indexOf(".");
out.println("<td>"+one.substring(0 , i)+"."+"</td>");
}

Splitting array on new line

I am submitting the following input through stdin:
4 2
30 one
30 two
15 three
25 four
My code is:
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String submittedString;
System.out.flush();
submittedString = stdin.readLine();
zipfpuzzle mySolver = new zipfpuzzle();
mySolver.getTopSongs(submittedString);
}
Which calls:
//Bringing it all together
public String getTopSongs(String myString) {
setUp(myString);
calculateQuality();
qualitySort();
return titleSort();
}
Which calls
public void setUp(String myString) {
String tempString = myString;
//Creating array where each element is a line
String[] lineExplode = tempString.split("\\n+");
//Setting up numSongsAlbum and songsToSelect
String[] firstLine = lineExplode[0].split(" ");
numSongsAlbum = Integer.parseInt(firstLine[0]);
songsToSelect = Integer.parseInt(firstLine[1]);
System.out.println(lineExplode.length);
//etc
}
However, for some reason lineExplode.length returns value 1... Any suggestions?
Kind Regards,
Dario
String[] lineExplode = tempString.split("\\n+");
The argument to String#split is a String that contains a regular expression
Your String#split regex will work file on Strings with newline characters.
String[] lineExplode = tempString.split("\n");
The problem is that your tempString has none of these characters, hence the size of the array is 1.
Why not just put the readLine in a loop and add the Strings to an ArrayList
String submittedString;
while (!(submittedString= stdin.readLine()).equals("")) {
myArrayList.add(submittedString);
}
Are you sure the file is using UNIX-style line endings (\n)? For a cross-platform split, use:
String[] lineExplode = tempString.split("[\\n\\r]+");
You should use "\\n" character to separate by new line but check that not all OS use the same separators ( http://en.wikipedia.org/wiki/Newline )
To solve this is very useful the system property line.separator that contains the current separator charater(s) for the current OS that is running the application.
You should use:
String[] lineExplode = tempString.split("\\\\n");
using \n as separator
Or:
String lineSeparator = System.getProperty("line.separator");
String[] lineExplode = tempString.split(lineSeparator);
Using the current OS separator
Or:
String lineSeparator = System.getProperty("line.separator");
String[] lineExplode = tempString.split(lineSeparator + "+");
Using the current OS separator and requiring one item
Its better to use this split this way:
String[] lineExplode =
tempString.split(Pattern.quote(System.getProperty("line.separator")) + '+');
To keep this split on new line platform independent.
UPDATE: After looking at your posted code it is clear that OP is reading just one line (till \n) in this line:
submittedString = stdin.readLine();
and there is no loop to read further lines from input.

Categories