I use the following code:
if (delanaloge.equals(stari)) {
if (novi.equals("-")) {
zdruzen = " -";
} else {
zdruzen = zdruzen + " " + " - " + novi + "\r";
}
nap = true;
}
\r is appended to create a line break, but it does not generate a line break like I expect. I would like to generate an output similar to this:
- 213
- 232
- 1321
How can I add a line break in my string?
you could use this:
public static String newline = System.getProperty("line.separator");
New line character combinations vary between OS. Windows is \r\n, Unix-like systems such as Linux, FreeBSD, Android and so on is \n and MacOS is \r.
Try whichever suits your development environment.
Try this:
if (delanaloge.equals(stari)) {
if (novi.equals("-")) {
zdruzen = " -";
} else {
zdruzen = zdruzen + " - " + novi + System.getProperty("line.separator");
}
nap = true;
}
try to use \r\n, in some cases \n will work (or every case) .. just try both :)
In JTextPane and other text components \n suffices and seems a good choice. On Windows the document internally stores \r\n so document positions and getText() indices are not equal. System.getProperty("line.separator") is more correct, but \n is so universal.
Use \ n for line breaking in printing the String.
if (delanaloge.equals(stari)) {
if (novi.equals("-")) {
zdruzen = " -";
} else {
zdruzen = zdruzen + " " + " - " + novi + "\n";
}
nap = true;
}
A bit from the typing machines age -
\r is the carriage return and should go back to the line origin.
\n is the new line feed on and does create the new line.
For Windows systems \r\n is a typical new line - and works as on the typing machine - carriage return, then new line.
For Linux based systems it was shorten to just \n. But '\n' is normally recognized by most programs.
Related
I have a TextArea that has some prompt text that I want to be split onto a few different lines, however, line breaks don't work in prompt text for some reason.
Code:
TextArea paragraph = new TextArea();
paragraph.setWrapText(true);
paragraph.setPromptText(
"Stuff done today:\n"
+ "\n"
+ "- Went to the grocery store\n"
+ "- Ate some cookies\n"
+ "- Watched a tv show"
);
Result:
As you can see, the text does not line break properly. Does anyone know how to fix this?
The prompt is internally shown by a node of type Text which can handle line breaks. So the interesting question is why don't they show? Reason is revealed by looking at the promptText property: it is silently replacing all \n with empty strings:
private StringProperty promptText = new SimpleStringProperty(this, "promptText", "") {
#Override protected void invalidated() {
// Strip out newlines
String txt = get();
if (txt != null && txt.contains("\n")) {
txt = txt.replace("\n", "");
set(txt);
}
}
};
A way around (not sure if it is working on all platforms - does on my win) is to use the \r instead:
paragraph.setPromptText(
"Stuff done today:\r"
+ "\r"
+ "- Went to the grocery store\r"
+ "- Ate some cookies\r"
+ "- Watched a tv show"
);
I have a logging function in CSharp and Java that I use in walking the stack. How do I make each log print to a new line only. Below are my Java and CSharp Functions.
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters );
}
the java version is this
public static void LogFunctionCall(string parameters,
[System.Runtime.CompilerServices.CallerMemberName] string methodName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
var stackFrame = new StackFrame(1);
var callerMethod = stackFrame.GetMethod();
var className = callerMethod.DeclaringType;
System.Diagnostics.Trace.WriteLine("CCCCCCCCCCCCCCCC" + " " + className + " " + methodName + " " + sourceLineNumber + " " + parameters + "\n");
}
I code on a windows machine.
Please where exactly do I need to place the new line character. I tried this
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters + "\n" );
}
but I still saw some of the logs being clumped up on a single line.
Instead of \n, try \r\n (carriage return and newline). Some text editors will display differently, so the newline may be in there, but whatever app you're using to read the logs might not be displaying it correctly.
You could also try
System.lineSeparator();
I've seen instances where the /n won't work but the lineSep does.
Also, because it hasn't been mentioned, Environment.NewLine will give you the new line character that is configured for the current environment.
I build a simple notepad. It has to count chars without space and "\n".
When I use space in program it does not count " ", but after when I write chars the program count this and the space.
#Override
public void keyTyped(KeyEvent e) {
a.setText("Counts :" + c.getText().trim().length());
b.setText("Words :");
}
You could replace all the spaces and then check the length
a.setText("Counts :" + c.getText().replace(" ", "").length());
You can use replaceAll() which can accept to use a regex, for example :
a.setText("Counts :" + c.replaceAll("\\s*\\n*", "").length());
Input
simple text \n simple text \n
Output
text = "simpletextsimpletext"
length = 20
I want the "Module Code = " and "Result = " to be separated by a tab but whenever I run the code below it literally just outputs
"Module Code = Biology\tResult = 40.0"
public String toString()
{
return "Module Code = " + moduleCode + "\t" + "Result = " + result;
}
The problem is that you're viewing the value of the produced string in the BlueJ window. That window is good for debugging purposes, but it won't exhibit the same behavior that a proper output device would, especially with respect to characters such as newline, tabulation, etc. Those characters will still appear with their escape sequences, just like you typed them in your source code.
In other words, your toString() method is fine and it works as intended. If you want to see its results formatted properly, don't view them using BlueJ -- print them somewhere else. The console is a good choice:
System.out.println(module.toString());
Why won't “\t” create a new line?
well, that is because “\t” is a tabulation not a new line “\n”
if you need a new line try instead
return "Module Code = " + moduleCode + "\n" + "Result = " + result;
How to remove multiple spaces and newlines in a string, but preserve at least one blank line for each group of blank lines.
For example, change:
"This is
a string.
Something."
to
"This is
a string.
Something."
I'm using .trim() to strip whitespace from the beginning and end of a string, but I couldn't find anything for removing multiple spaces and newlines in a string.
I would like to keep just one whitespace and one newline.
The one-line solution to remove multiple spaces/newlines, but preserve at least one blank line from multiple blank lines:
str = str.replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
Each individual line is trimmed too.
Here's some test code:
String str = " This is\r\n " +
"\r\n" +
" \r\n " +
" \r \n \n " +
"\r\n" +
" a string. ";
str = str.trim().replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
System.out.println(str);
Output:
This is
a string.
The previous advice will trim all whitespace, including the linefeeds and replace them with a single space.
text.replaceAll("\\n\\s*\\n", "\\n").replaceAll("[ \\t\\x0B\\f]+", " ").trim());
First it replaces any instances of linefeeds with only whitespace between them with a single linefeed, then it trims down any other whitespace to a single space ignoring linefeeds.
Here is what I came up with after a bit of testing...
public String keepOneWS(String str) {
Pattern p = Pattern.compile("(\\s+)");
Matcher m = p.matcher(str);
Pattern pBlank = Pattern.compile("[ \t]+");
String newLineReplacement = System.getProperty("line.separator") +
System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
while (m.find()) {
if(pBlank.matcher(m.group(1)).matches()) {
m.appendReplacement(sb, " ");
} else {
m.appendReplacement(sb, newLineReplacement);
}
}
m.appendTail(sb);
return sb.toString().trim();
}
public void testKeepOneWS() {
String str = " This \t is\r\n " +
"\r\n" +
" \r\n " +
" \r \n \t \n " +
"\r\n" +
" a \t string. \t ";
String expected = "This is" + System.getProperty("line.separator")+
System.getProperty("line.separator") + "a string.";
String actual = keepOneWS(str);
System.out.println("'" + actual + "'");
assertEquals(expected, actual);
}
After a goup of whitespace is captured, it is checked whether it consists only of spaces, if yes then that goup is replaced by one single space, otherwise the goup consits of spaces and line terminators, in this case the group is replaced by one line terminator.
The output is:
'This is
a string.'