Java:为什么检查“\n”不能匹配使用System.getProperty(“line.separator”)添加的换行符

8

(更新的问题)

首先,我认为"\n"等同于System.getProperty("line.separator")

我编写了一些用于处理字符串的方法,其中一些方法检查是否存在换行符。

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

但是我注意到检查"\n"并不匹配使用System.getProperty("line.separator")添加的换行符。

这是一个SSCCE,以证明我的说法!:

描述:
两个完全相同的文本字符串;一个使用"\n"添加了新行,另一个使用System.getProperty("line.separator")添加了新行。

有一个名为String removeExtraNewLines(String)的方法,用于删除字符串中的任何额外换行符并将其返回;正如其标题所示。使用此方法过滤的两个字符串。

两个按钮buttonAlphabuttonBeta分别使用过滤后的字符串设置JTextArea的文本

您会注意到,该方法捕获/匹配并删除alpha_String的额外换行符,但不会对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();
            }
        });
    }
}

问题:为什么使用"\n"检查不匹配使用System.getProperty("line.separator")添加的换行符?如何匹配它们?


1
你是否验证过在你的系统中,System常量确实等于'\n'?这不需要更多的复杂对比即可发现,对吧? - BlackVegetable
1
首先,您正在使用哪个操作系统进行测试?其次,if (string.charAt(i) == System.getProperty("line.separator")) 是否与您的预期不符?第三,您是否尝试使用调试器来检查 System.getProperty("line.separator") 的实际值是什么? - Jesse Webb
这篇文章可能会引起您的兴趣:http://en.wikipedia.org/wiki/Newline - Pshemo
1
你开了一个悬赏,但没有解释为什么得票最高的答案不能回答你的问题。\n是平台相关的,System.getProperty("line.separator")可能是\n\r\n - assylias
@assylias Jon Skeet说:“你试图检查什么并不是很清楚”,所以我用SSCCE更新了我的问题,我认为如果问题变得更加清晰,答案会有所不同。谢谢。 - Saleh Feek
1个回答

20
首先,我认为 "\n" 可以等价于 System.getProperty("line.separator"),只是后者可以在不同平台上使用。
不,后者是特定于平台的。它是获取您所在平台换行符的平台无关方式。
例如,在Windows上,我期望 System.getProperty("line.separator") 返回 "\r\n"。
至于你的textArea用于换行的内容 - 这完全取决于 textArea 是什么 - 而你没有给我们任何信息。

10
@BlackVegetable:苛求细节是成为一名软件工程师的重要组成部分 :) - Jon Skeet
我现在要引用你的话! - BlackVegetable
textArea 是 JTextArea 对象。根据您的回答,那么我必须检查是否匹配字符串 "\r\n",这需要在字符串中检查两个连续的字符;一些代码像 if((string.charAt(i) == '\r')&&((string.charAt(i++) == '\n')) - Saleh Feek
1
@SalehFeek:不太清楚您想要检查什么。但是您应该阅读http://docs.oracle.com/javase/7/docs/api/javax/swing/text/DefaultEditorKit.html。 - Jon Skeet
我只是在搜索换行符"\n",使用条件if(string.charAt(i) == '\n') {// do something};但是这种方法无法匹配使用System.getProperty("line.separator")添加的换行符。也就是说,对于相同的JTextArea和相同的条件if(string.charAt(i) == '\n');当使用append("\n")添加换行符时,它们会被搜索条件匹配,但是当我使用append(System.getProperty("line.separator"))时,搜索条件无法匹配这些新的换行符。我将避免使用System.getProperty("line.separator"),而使用"\n"代替。谢谢帮助。 - Saleh Feek
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接