【问题标题】:Java: Why checking for "\n" doesn't match new lines added using System.getProperty("line.separator")Java:为什么检查“\n”与使用 System.getProperty("line.separator") 添加的新行不匹配
【发布时间】:2013-01-07 07:28:32
【问题描述】:

更新问题

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

我写了一些方法来处理字符串,其中一些检查新行的存在

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

但我注意到检查 "\n"System.getProperty("line.separator") 添加的新行不匹配

这是一个SSCCE来证明我的主张!

说明:
两串相同的文本;一个alpha_String 使用"\n" 添加了新行,另一个beta_String 使用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") 添加的新行?,以及如何匹配它们?

【问题讨论】:

  • 您是否验证过,在您的系统上,System 常量实际上等于'\n'?只需进行简单的比较即可发现,对吧?
  • 首先,您使用哪个操作系统来测试这个?其次,if (string.charAt(i) == System.getProperty("line.separator")) 没有按您的预期工作吗?第三,您是否尝试过使用调试器检查 System.getProperty("line.separator") 的实际值是多少?
  • 这篇文章你可能会感兴趣en.wikipedia.org/wiki/Newline
  • 您打开了赏金,但没有解释为什么最受欢迎的答案没有回答您的问题。 \n 取决于平台,System.getProperty("line.separator") 可以是 \n\r\n
  • @assylias Jon Skeet 说“根本不清楚你要检查什么”所以我用 SSCCE 更新了我的问题,我认为如果问题变得更清楚,答案会有所不同.谢谢

标签: java newline


【解决方案1】:

首先,我认为 "\n" 等价于 System.getProperty("line.separator") ,只是后者是平台无关的。

不,后者是特定于平台的。这是获取平台行分隔符的平台无关方式。

例如,在 Windows 上,我希望 System.getProperty("line.separator") 返回“\r\n”。

现在,至于您的 textArea 用于换行符的用途 - 这完全取决于 textArea 是什么 - 而您还没有向我们提供任何相关信息。

【讨论】:

  • @BlackVegetable:Pedantry 是成为软件工程师的重要组成部分 :)
  • 我现在要引用你的话!
  • textArea 是JTextArea。根据您的回答,我必须检查字符串“\r\n”是否匹配,这需要检查字符串中的两个连续字符;一些代码,如if((string.charAt(i) == '\r')&amp;&amp;((string.charAt(i++) == '\n'))
  • @SalehFeek:根本不清楚您要检查什么。但你应该阅读docs.oracle.com/javase/7/docs/api/javax/swing/text/…
  • 我只是在搜索 newline "\n",使用 -> if(string.charAt(i) == '\n') {// do something};这不适用于使用 System.getProperty("line.separator") 添加的换行符。这意味着对于 smae JTextArea 和相同的条件if(string.charAt(i) == '\n');当使用 append("\n") 为 JTextArea 提供新行时,它们与搜索条件匹配,但是当我使用 append(System.getProperty("line.separator")) 时,搜索条件与这些新行不匹配。我将避免使用System.getProperty("line.separator") 代替"\n" 感谢提供帮助。
猜你喜欢
  • 1970-01-01
  • 2016-02-03
  • 2016-08-16
  • 2011-03-31
  • 1970-01-01
  • 2020-05-16
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多