Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why checking for "\n" doesn't match new lines added using System.getProperty("line.separator")

Tags:

java

newline

(Updated Question)

First, I think that "\n" is equivalent to System.getProperty("line.separator")

I wrote some methods to work with Strings some of them check for existence of new line

if (string.charAt(i) == '\n') {//do something;}

But I noticed that checking for "\n" doesn't match the new lines added by the System.getProperty("line.separator")

This is an SSCCE to demonstrate my claim!:

Description:
Two strings of identical text; one alpha_String has new lines added using "\n", and the other beta_String has new lines added using System.getProperty("line.separator")

There is a method named String removeExtraNewLines(String) used to remove any extra new lines in a String and return it back; as its header suggests. The two strings filtered using this method.

The two buttons buttonAlpha and buttonBeta each set the text of the JTextArea with the filtered String

You will notice that the the method catch/match and remove extra new lines of alpha_String but don't do the same with beta_String

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class NewLineTest extends JPanel
{

    JPanel buttonPanel;
    JPanel textAreaPanel;
    JButton buttonAlpha;
    JButton buttonBeta;
    JTextArea textArea;
    String n = "\n";
    String s = System.getProperty("line.separator");
    String alpha_String;
    String beta_String;

    public NewLineTest()
    {
        createSentencesText();
        buttonAlpha = new JButton("Alpha String");
        buttonAlpha.addActionListener(eventWatcher);

        buttonBeta = new JButton("Beta String");
        buttonBeta.addActionListener(eventWatcher);

        textArea = new JTextArea(0, 0);
        JScrollPane scrollTextArea = new JScrollPane(textArea);
        scrollTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        textArea.setEditable(false);

        buttonPanel = new JPanel();
        textAreaPanel = new JPanel(new BorderLayout());

        buttonPanel.add(buttonAlpha);
        buttonPanel.add(buttonBeta);

        textAreaPanel.add(scrollTextArea, BorderLayout.CENTER);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textAreaPanel, buttonPanel);
        splitPane.setDividerLocation(400);
        splitPane.setResizeWeight(.5d);
        this.setLayout(new BorderLayout());
        this.add(splitPane);
    }

    private void createSentencesText()
    {
        alpha_String = "A: Let’s go to the beach." + n + n
                + "B: That’s a great idea." + n
                + "A: We haven’t been in a while." + n + n
                + "B: We haven’t been in a month." + n
                + "A: The last time we went, you almost drowned." + n
                + "B: No, I didn’t." + n + n + n
                + "A: Then why did the lifeguard dive into the water?" + n
                + "B: I think he wanted to cool off." + n
                + "A: He swam right up to you." + n
                + "B: And then he turned right around." + n
                + "A: Maybe you’re right." + n
                + "B: Maybe we should get going.";


        beta_String = "A: Let’s go to the beach." + s + s
                + "B: That’s a great idea." + s
                + "A: We haven’t been in a while." + s + s
                + "B: We haven’t been in a month." + s
                + "A: The last time we went, you almost drowned." + s
                + "B: No, I didn’t." + s + s + s
                + "A: Then why did the lifeguard dive into the water?" + s
                + "B: I think he wanted to cool off." + s
                + "A: He swam right up to you." + s
                + "B: And then he turned right around." + s
                + "A: Maybe you’re right." + s
                + "B: Maybe we should get going.";
    }

    public static String removeExtraNewLines(String s)
    {
        String myNewString = s.trim();
        StringBuilder stringB = new StringBuilder();

        char previouseChar = '~';
        for (int i = 0; i < myNewString.length(); i++)
        {
            if (i > 1)
            {
                previouseChar = myNewString.charAt(i - 1);
            }
            if ((myNewString.charAt(i) == '\n') && (previouseChar == '\n'))
            {
                continue;
            }

            stringB.append(myNewString.charAt(i));
        }
        myNewString = stringB.toString();
        return myNewString;
    }
    AbstractAction eventWatcher = new AbstractAction()
    {
        @Override
        public void actionPerformed(ActionEvent ae)
        {
            Object source = ae.getSource();
            if (source == buttonAlpha)
            {
                String arranged_string_alpha = removeExtraNewLines(alpha_String);
                textArea.setText(arranged_string_alpha);
            }
            if (source == buttonBeta)
            {
                String arranged_string_beta = removeExtraNewLines(beta_String);
                textArea.setText(arranged_string_beta);
            }
        }
    };

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("NewLine Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 300);
        frame.add(new NewLineTest(), BorderLayout.CENTER);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

So the question: Why checking for "\n" doesn't match new lines added using System.getProperty("line.separator")?, And How to match them?

like image 978
Saleh Feek Avatar asked Jan 23 '13 17:01

Saleh Feek


People also ask

What is the equivalent of \n in Java?

\n and 0xa are exactly the same thing.

How do you identify a new line character in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What does line separator do in Java?

The lineSeparator() is a built-in method in Java which returns the system-dependent line separator string. It always returns the same value – the initial value of the system property line.


1 Answers

First, I think that "\n" is equivalent to System.getProperty("line.separator") except that the later is platform independent.

No, the latter is platform-specific. It's the platform-independent way of getting your platform's line separator.

So on Windows, I'd expect System.getProperty("line.separator") to return "\r\n", for example.

Now as for what your textArea uses for a new-line - that entirely depends on what textArea is - and you haven't given us any information about that.

like image 141
Jon Skeet Avatar answered Oct 24 '22 06:10

Jon Skeet