How to obtain text from a String variable? - java

String s = System.lineSeparator();
System.out.println(s);
I try to obtain text from variable s, but why is there no text in variable s ?

Try following code on your system
for(byte b : System.lineSeparator().getBytes()){
System.out.println(b);
}
It will print either
10
OR
13
10
Here I print the ascii code for whatever I got from System.lineSeparator().
ascii code for \n is 10 and for \r is 13.
It is also given in documentation of System.lineSeparator()
On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
So the point is you didn't see any output because if you try to print \r or \n because \r represents line feed and \n represents next line. And you cannot see them on console. But they will have their effects in strings.

The System.lineSeparator(); returns a string that the system uses to generally separate lines in, say for example, an input from the Standard Input.
This is generally a new line character and so when you print it in your program, you will not "See" it as is.
Try using this:
String s = System.lineSeparator();
System.out.println("~~" + s + "~~");
This will help you distinguish the output. You should see something like this:
~~
~~
This output would indicate the the new line character is separating the ~~ characters in your print statement.
Hope this helps!

System.lineSeperator() will mostly return "\r\n", so when you sysout it actualy prints a new line.

Related

Escape character '\' doesn't show in System.out.println() but in return value

In Java, when I replace characters in a String with escaped-characters, the characters show up in the return value, although they were not there according to System.out.println.
String[][][] proCategorization(String[] pros, String[][] preferences) {
String str = "wehnquflkwe,wefwefw,wefwefw,wefwef";
String strReplaced = str.replace(",","\",\""); //replace , with ","
System.out.println(strReplaced);
The console output is: wehnquflkwe","wefwefw","wefwefw","wefwef
String[][][] array3d = new String[1][1][1]; // initialize 3d array
array3d[0][0][0] = strReplaced;
System.out.println(array3d[0][0][0]);
return array3d;
}
The console output is:
wehnquflkwe","wefwefw","wefwefw","wefwef
Now the return value is:
[[["wehnquflkwe\",\"wefwefw\",\"wefwefw\",\"wefwef"]]]
I don't understand why the \ show up in the return value but not in the System.out.println.
Characters in memory can be represented in different ways.
Your integrated development environment (IDE) has a debugger that chooses to represent a String[][][] with a single element that contains the characters
wehnquflkwe","wefwefw","wefwefw","wefwef
as a java-quoted string
"wehnquflkwe\",\"wefwefw\",\"wefwefw\",\"wefwef"
this makes a lot of sense, because you can then copy and paste this string into java code without any loss.
On the other hand, your system's console, and the IDE's built-in terminal emulator, will output the characters in their normal representation, that is, without any java string-escape-characters:
wehnquflkwe","wefwefw","wefwefw","wefwef
As an experiment, you may want to check what happens with other "special" characters, such as \t (a tab break) or \b (backspace). This is just the tip of the iceberg - characters in Java generally translate into unicode points, which may or may not be supported by the fonts available in your system or terminal. The IDE's way of representing characters as java-quoted strings allows it to losslessly represent pretty much anything; System.out.println's output is a lot more variable.
System.out.println prints the String exactly as it is stored in memory.
On the other hand, when you stop the application flow using a breakpoint you are able to look up the values.
Most of the IDEs display escape characters with \ to indicate that it's just one String, not String[] in this case, or not to split the String into two lines if it contains \n in the middle.
Just in case, you still have doubts, I suggest printing strReplaced.length(). This should allow you to count characters one by one.
Possible experiments:
String s = "my cute \n two line String";
System.out.println(s + " length is: " + s.length());

Java, end of line with system.out.print

I have done some research concerning System.out.print() and System.out.println() and I discovered that System.out.println() add the end of line at the end of printed line.
System.out.println("Test");
Output only :
Test
but does not print end of the line.
System.out.print("Test");
Output only:
Test
but does not end the line and leave some place for other words or numbers, etc etc.
A more illustrative way is:
Test_____________________________________________ (All "blank" spots)
Is there a way to, force an end of line with System.out.print() directly after the word Test? Will the usage of % will remove the "blank" spots?
Or a way to code a function that will end the line after I used several System.out.print() to print a sentence?
For exemple :
System.out.print("Test);
System.out.print("Test);
will outpost a pure:
Test Test
like System.out.println("Test Test")
You can append line separator, Note that it is platform dependant, so :
Windows ("\r\n")
Unix/Linux/OSX ("\n")
pre-OSX Mac ("\r")
If you want to get line separator depending on actual system you can just use :
System.getProperty("line.separator"); for pre Java 7
System.lineSeparator(); for Java 7
Then you just append your separator to your string in System.out.print, like :
System.out.print("Word\n");
You can do System.out.print("Test\n").
System.out.println("Test"); will print end of the line. When you don't see it in your IDE it doesn't mean it isn't here. Try:
System.out.println("Test1");
System.out.println("Test2");
System.out.println("Test3");
which will produce:
Test1
Test2
Test3
From the docu of the println(String):
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println()
and from the docu of the println():
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
For getting an OS independent EOL character you could try
System.getProperty("line.separator");
and then appending that to your string ?
Why do you want to manually do that though since there is a function to do it for you ?
You can explicitly include a newline char in what you are printing:
System.out.print("Test\n");
This will force the newline while using the print function.
You can force a manual newline like so:
System.out.print("Test\n");
You can also mix the two when you need to print then end the line like so:
System.out.print("This is on ");
System.out.print("the same line.");
System.out.println(" and now we'll end the line");
System.out.println("This is on a different line.");

How to split string with empty new line

my file contains this string:
a
b
c
now I want to read it and split it with empty line so I have this:
text.split("\n\n"); where text is output of file
problem is that this doesnt work. When I convert new line to byte I see that "\n\n" is represented as 10 10 but new line in my file is represented by 10 13 10 13. So how I can split my file ?
Escape Description ASCII-Value
\n New Line Feed (LF) 10
\r Carriage Return (CR) 13
So you need to try string.split("\n\r") in your case.
Edit
If you want to split by empty line, try \n\r\n\r. Or you can use .readLine() to read your file, and skip all empty lines.
Are you sure it's 10 13 10 13? It always should be 13 10...
And, you should not depend on line.separator too much. Because if you are processing some files from *nix platform, it's \n, vice versa. And even on Windows, some editors use \n as the new line character. So I suggest you to use some high level methods or use string.replaceAll("\r\n", "\n") to normalize your input.
Keep in mind, sometimes you have to use:
System.getProperty("line.separator");
to get the line separator, if you want to make it platform independent. You can also use BufferedWriter's newLine() method, that takes care of that automatically.
Try using:
text.split("\n\r");
Why are you splitting on \n\n?
You should be splitting on \r\n because that's what the file lines are separated by.
Try to use regular expressions, something like:
text.split("\\W+");
text.split("\\s+");
LF: Line Feed, U+000A
CR: Carriage Return, U+000D
so you need to try to use
"string".split("\r\n");
Use scanner object, instead of worrying about chars/bytes.
One Solution is to Split using "\n" and neglect empty Strings
List<String> lines = text.split("\n");
for(String line : lines) {
line = line.trim();
if(line != "") {
System.out.println(line);
}
}

How to change "\\r\\n" to line separator in java

I am working on a school project to build a pseudo terminal and file system. The terminal is scanning System.in and pass the string to controller.
Input to console: abc\r\nabc\r\nabc
Here is the code I tried
Scanner systemIn = Scanner(System.in);
input = systemIn.nextLine();
input = input.replaceAll("\\\\r\\\\n",System.getProperty("line.separator"));
System.out.print(input);
I want java to treat the \r\n I typed to console as a line separator, not actually \ and r.
What it does now is print the input as is.
Desired Ouput:
abc
abc
abc
UPDATE: I tried input = StringEscapeUtils.unescapeJava(input); and it solved the problem.
You need to double-escape the regexes in java (once for the regex backslash, once for the Java string). You dont want a linebreak (/\n/, "\\n"), but a backslash (/\\/) plus a "n": /\\n/, "\\\\n". So this should work:
input.replaceAll("(\\\\r)?\\\\n", System.getProperty("line.separator"));
For a more broad handling of escape sequences see How to unescape a Java string literal in Java?
If your input has the string '\r\n', try this
Scanner systemIn = Scanner(System.in);
input = systemIn.nextLine();
input = input.replaceAll("\\\\r\\\\n",System.getProperty("line.separator"))
For consistent behaviour I would replace \\r with \r and \\n with \n rather than replace \\r\\n with the newline as this will have different behaviour on different systems.
You can do
input = systemIn.nextLine().replaceAll("\\\\r", "\r").replaceAll("\\\\n", "\n");
nextLine() strips of the newline at the end. If you want to add a line separator you can do
input = systemIn.nextLine() + System.getProperty("line.separator");
if you are using println() you don't need to add it back.
System.out.println(systemIn.nextLine()); // prints a new line.
As it was mentioned by r0dney, the Bergi's solution doesn't work.
The ability to use some 3rd party libraries is good, however for a person who studies it is better to know the theory, because not for every problem exists some 3rd party library.
Overload project with tons of 3rd party libraries for tasks which can be solved in one line code makes project bulky and not easy maintainable. Anyway here is what's working:
content.replaceAll("(\\\\r)?\\\\n", System.getProperty("line.separator"));
Unless you are actually typing \ and r and \ and n into the console, you don't need to do this at all: instead you have a major misunderstanding. The CR character is represented in a String as \r but it consists of only one byte with the hex value 0xD. And if you are typing backslashes into the console, the simple answer is "don't". Just hit the Enter key: that's what it's for. It will transmit the CR byte into your code.

How to create a String with carriage returns?

For a JUnit test I need a String which consists of multiple lines. But all I get is a single lined String. I tried the following:
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
I also tried \n\r instead of \n. System.getProperty("line.separator") doesn't work too. it produces a \n in String and no carriage return. So how can I solve that?
It depends on what you mean by "multiple lines". Different operating systems use different line separators.
In Java, \r is always carriage return, and \n is line feed. On Unix, just \n is enough for a newline, whereas many programs on Windows require \r\n. You can get at the platform default newline use System.getProperty("line.separator") or use String.format("%n") as mentioned in other answers.
But really, you need to know whether you're trying to produce OS-specific newlines - for example, if this is text which is going to be transmitted as part of a specific protocol, then you should see what that protocol deems to be a newline. For example, RFC 2822 defines a line separator of \r\n and this should be used even if you're running on Unix. So it's all about context.
The fastest way I know to generate a new-line character in Java is: String.format("%n")
Of course you can put whatever you want around the %n like:
String.format("line1%nline2")
Or even if you have a lot of lines:
String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")
Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.
Do this:
Step 1: Your String
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
Step 2: Just replace all "\n" with "%n" the result looks like this
String str = ";;;;;;%n" +
"Name, number, address;;;;;;%n" +
"01.01.12-16.02.12;;;;;;%n" +
";;;;;;%n" +
";;;;;;";
Notice I've just put "%n" in place of "\n"
Step 3: Now simply call format()
str=String.format(str);
That's all you have to do.
Try append characters .append('\r').append('\n'); instead of String .append("\\r\\n");
Thanks for your answers. I missed that my data is stored in a List<String> which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.

Categories