比较两个字符串并突出显示不匹配的位置

时间:2014-11-18 04:47:54

标签: java string

我想比较两个字符串并突出显示不匹配的字词。

我编写的代码有以下两个问题:

1。只要存在不匹配,该词就会存储在“令牌”中。但是一旦突出显示函数被调用,它就会突出显示该字符串中与令牌中的单词匹配的所有单词。

2。所有差异都显示在控制台上。但是,在GUI加载时,只会突出显示数组索引中的最后一个值,从而不会显示先前的高亮显示。

到目前为止,这是守则。我还附上了快照以供参考。任何建议都会有很大帮助。感谢:

package com.check;

import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class highlightCheck {

int i, j, x;

int Flag;
  int length;
 //int errorIndex;

int errorIndex[] = new int[2];
int loop;

String s1 = "";
String s2 = "";

String Retext1 = "Extreme programming is one approach of agile software development which emphasizes on frequent releases on short development cycles which are called time boxes. This result in reducing the costs spend for changes, by having multiple short development cycles, rather than one long one. Extreme programming includes pair-wise programming (for code review, unit testing).Also it avoids implementing features which are not included in the current time box, so the schedule creep can be minimized.";
String Retext2 = "Extreme programming is one approach of agile software development which emphasizes on frequent releases in short development cycles which are called time boxes. This result in reducing the costs spend for changes, by having multiple short development cycles, rather than one long one. Extreme programming includes pair-wise programming (for code review, unit testing).Also it avoids implementing features which are not included in the current time box, so the schedule creep can be minimized.";


String token1;
String token2;

public static void main(String args[]) {

    try {

        SwingUtilities.invokeAndWait(new Runnable() {

            public void run() {
                new highlightCheck().createAndShowGUI();
            }
        });

    } catch (InterruptedException ex) {
        ex.printStackTrace();

    } catch (InvocationTargetException ex) {
        ex.printStackTrace();
    }
}

public void createAndShowGUI() {

    JFrame frame = new JFrame("Error-Highlighter");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    JTextField field = new JTextField();
    field.setBounds(60,  100,  60,  80);
    field.setSize(new Dimension(500,200));
    field.setBackground(Color.LIGHT_GRAY);
    field.setVisible(true);                 


    field.setEditable(false);


    frame.add(field);

    JTextArea area = new JTextArea(30, 50);
    area.setLineWrap(true);
    area.setWrapStyleWord(true);
    area.setEditable(false);


    for(i = 0; i < Retext1.length(); i++) {         

        char splitArray1 [] = Retext1.toCharArray();  

        s1 = s1 + splitArray1[i];           
    }


    System.out.println(s1.charAt(s1.length() - 1));
    area.setText(s1);


    for(j = 0; j < Retext2.length(); j++) {         

        char splitArray2 [] = Retext2.toCharArray();  

        s2 = s2 + splitArray2[j];           
    }

    System.out.println(s2.charAt(s2.length() - 1));
    field.setText(s2);




    String SplitArray1[] = Retext1.split(" ");
    String SplitArray2[] = Retext2.split(" ");

    //System.out.println(SplitArray1.length);

  if(SplitArray1.length > SplitArray2.length)  
      length = SplitArray1.length;
  else if(SplitArray2.length > SplitArray1.length)
      length = SplitArray2.length;
  else length = SplitArray2.length;


          for(x = 0; x < length; x++) { 

        if(SplitArray1[x] == SplitArray2[x]) 
            continue;

        else if(!SplitArray1[x] .equals(SplitArray2[x])) {



                token1 = "" + SplitArray1[x];
                token2 = "" + SplitArray2[x];


                System.out.print(x);
                System.out.print("  :  ");
                System.out.print(token1);
                System.out.print("  :  ");
                System.out.print(token2);
                System.out.println();

                highlight(area, token1);                             
                highlight(field, token2);                       

            }   

       }      


    frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);               
    frame.pack();
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
}


public void highlight(JTextComponent textComp, String pattern) {

    removeHighlights(textComp);

    try {

        Highlighter hilite = textComp.getHighlighter();
        Document doc = textComp.getDocument();
        String text = doc.getText(0, doc.getLength());

        int position = 0;

        while ((position = text.indexOf(pattern, position)) >= 0) {

            hilite.addHighlight(position, position + pattern.length(), myHighlightPainter);
            position += pattern.length();
        }

    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}


public void removeHighlights(JTextComponent textComp) {


    Highlighter hilite = textComp.getHighlighter();
    Highlighter.Highlight[] hilites = hilite.getHighlights();

     for (int i = 0; i < hilites.length; i++) {

         if (hilites[i].getPainter() instanceof MyHighlightPainter) {
            hilite.removeHighlight(hilites[i]);
        }
    }
}

Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);


class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {

    public MyHighlightPainter(Color color) {

        super(color);

    }
  }
}

1 个答案:

答案 0 :(得分:2)

而不是试图在Document中找到可能多次出现的令牌(因为您没有提供可以确定您正在谈论的令牌的上下文),您可以简单地比较两个Documents更直接,保持当前的位置偏移,你正在进行比较......

int max = Math.min(doc1.getLength(), doc2.getLength());
int startPos = 0;
try {
    for (int pos = 0; pos < max; pos++) {

        if (doc1.getText(pos, 1).equals(" ")) {

            int endPos = pos;
            String parent = doc1.getText(startPos, endPos - startPos);
            String child = doc2.getText(startPos, endPos - startPos);
            if (!parent.equals(child)) {

                highlight(field, startPos, endPos);
                highlight(area, startPos, endPos);

            }

            startPos = endPos + 1;

        }

    }
} catch (BadLocationException exp) {
    exp.printStackTrace();
}

(注意,可能应该突出显示超出另一个文档末尾的任何文本,但你可以想出来;)

Highlight

import java.awt.Color;
import java.awt.GridLayout;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class HighlightCheck {

    private String Retext1 = "Extreme programming is one approach of agile software development which emphasizes on frequent releases on short development cycles which are called time boxes. This result in reducing the costs spend for changes, by having multiple short development cycles, rather than one long one. Extreme programming includes pair-wise programming (for code review, unit testing).Also it avoids implementing features which are not included in the current time box, so the schedule creep can be minimized.";
    private String Retext2 = "Extreme programming is one approach of agile software development which emphasizes on frequent releases in short development cycles which are called time boxes. This result in reducing the costs spend for changes, by having multiple short development cycles, rather than one long one. Extreme programming includes pair-wise programming (for code review, unit testing).Also it avoids implementing features which are not included in the current time box, so the schedule creep can be minimized.";

    private Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);

    public static void main(String args[]) {

        try {

            SwingUtilities.invokeAndWait(new Runnable() {

                public void run() {
                    new HighlightCheck().createAndShowGUI();
                }
            });

        } catch (InterruptedException ex) {
            ex.printStackTrace();

        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }

    public void createAndShowGUI() {

        JFrame frame = new JFrame("Error-Highlighter");
        frame.setLayout(new GridLayout(2, 1));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTextArea field = new JTextArea(5, 50);
        field.setText(Retext2);
        field.setLineWrap(true);
        field.setWrapStyleWord(true);
        field.setEditable(false);

        frame.add(new JScrollPane(field));

        JTextArea area = new JTextArea(5, 50);
        area.setText(Retext1);
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        area.setEditable(false);

        Document doc1 = field.getDocument();
        Document doc2 = area.getDocument();

        int max = Math.min(doc1.getLength(), doc2.getLength());
        int startPos = 0;
        try {
            for (int pos = 0; pos < max; pos++) {

                if (doc1.getText(pos, 1).equals(" ")) {

                    int endPos = pos;
                    String parent = doc1.getText(startPos, endPos - startPos);
                    String child = doc2.getText(startPos, endPos - startPos);
                    if (!parent.equals(child)) {

                        highlight(field, startPos, endPos);
                        highlight(area, startPos, endPos);

                    }

                    startPos = endPos + 1;

                }

            }
        } catch (BadLocationException exp) {
            exp.printStackTrace();
        }

        frame.getContentPane().add(new JScrollPane(area));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public void highlight(JTextComponent textComp, int startPos, int endPos) throws BadLocationException {

        Highlighter hilite = textComp.getHighlighter();
        hilite.addHighlight(startPos, endPos, myHighlightPainter);

    }

    class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {

        public MyHighlightPainter(Color color) {

            super(color);

        }
    }
}
相关问题