如何比较Java中特定值的两个String

时间:2017-02-15 11:41:05

标签: java string

我有两个不同XML生成的字符串。喜欢这个

s1= <xml><timestamp>10.22</timestamp></xml>
s2 = <xml><timestamp>10.24</timestamp></xml>

我需要比较这两个字符串并从这些字符串中删除特定标记,并比较字符串的其余部分是否相等。

示例:我想删除时间戳标记:然后s1和s2将如下所示:

s1= <xml></xml>
s2 = <xml></xml>

我不允许在此使用编组和解组api。我也写了一个代码,但它不处理嵌套标签。

public boolean compareString(final String s1, final String s2, String stringToBeRemoved) throws Exception {
        StringBuilder sb1 = new StringBuilder(s1);
        StringBuilder sb2 = new StringBuilder(s2);
        int intialstartIndex;

        //first String evaluation starts here
        int startIndex1 = sb1.indexOf(stringToBeRemoved);
        intialstartIndex = startIndex1;

        //handling for short expression to reach to the top of the starttag
        do {
            startIndex1--;
        } while(sb1.charAt(startIndex1) != '<');


        int endIndex1 = sb1.indexOf(stringToBeRemoved,intialstartIndex+stringToBeRemoved.length());
        endIndex1 = endIndex1 + stringToBeRemoved.length()+1;

        //handling for short expression to reach to end of close tag
        do {
            endIndex1++;
        } while(sb1.charAt(endIndex1) != '>');

        //second string evaluation starts here

        int startIndex2 = sb2.indexOf(stringToBeRemoved);
        intialstartIndex = startIndex2;
        do {
            startIndex2--;
        } while(sb2.charAt(startIndex1) != '<');


        int endIndex2 = sb2.indexOf(stringToBeRemoved,intialstartIndex+stringToBeRemoved.length());
        endIndex2 = endIndex2 + stringToBeRemoved.length()+1;

        do {
            endIndex2++;
        } while(sb2.charAt(endIndex2) != '>');

        if(startIndex1 == -1 || startIndex2 == -1){
    throw new Exception();
        }
        else {
            sb1 = sb1.delete(startIndex1,endIndex1);
            sb2 = sb2.delete(startIndex2,endIndex2);
        }
        return sb1.toString().equals(sb2.toString());

    }

任何帮助建议/任何工具都非常感谢。我也对正则表达式模式持开放态度。谢谢

0 个答案:

没有答案