Java判断数组中是否存在某字符串以及一个数组的值是否都在另一个数组

背景:

如有字符串: String certDn = "CN=00,GIVENNAME=11,STREET=22,DNQUALIFIER=33,TITLE=44,UID=55,C=CN";

判断等号左边的字符串是否为规定值。

package com.xdja.pki.test.util;

import java.util.Arrays;
import java.util.List;

/**
 * @author wly
 */
public class TestString {

    /**
     * 数组中是否存在某字符串
     * @param array
     * @param str
     * @return
     */
    public static boolean existStr(String[] array,String str){
        List aList = Arrays.asList(array);
        return aList.contains(str);
    }

    /**
     * 数组中是否存在某字符串
     * @param array
     * @param str
     * @return
     */
    public static boolean existStr1(String[] array,String str) {
        //Arrays的binarySearch方法必须应用于有序数组
        int res = Arrays.binarySearch(array, str);
        if (res > 0) {
            return true;
        }
        return false;
    }

    /**
     * 数组中是否存在某字符串
     * @param array
     * @param str
     * @return
     */
    public static boolean existStr2(String[] array,String str){
        for (String s : array) {
            if (s.equals(str)){
                return true;
            }
        }
        return false;
    }
    /**
     * 引申方法检查Dn关键字
     * @param certDn
     * @return
     */
    public static boolean checkDnKeyword(String certDn){

        String[] splits = certDn.split(",");
        String[] array = new String[]{"C","CN","L","O","OU","ST","DC","DNQUALIFIER","GIVENNAME","INITIALS","SN","STREET","TITLE","TELEPHONENUMBER","UID"};
        List aList = Arrays.asList(array);

        boolean isKeyword = true;
        for (String split:splits){
            String substring = split.substring(0,split.indexOf("="));
            substring = substring.toUpperCase();
            if(!aList.contains(substring)){
                isKeyword = false;
                break;
            }
        }
        return isKeyword;
    }

    /**
     * 判断一个数组中是否包含另一个数组的所有值
     *
     * @return
     */
    public static boolean existStr4(){
        String certDn = "CN=00,SN=11,INITIALS=22,TELEPHONENUMBER=33,GIVENNAME=44,STREET=55,DNQUALIFIER=66,TITLE=77,UID=88,DC=1234,OU=sha-1WithRSA1024,ST=ra,ST=CArsaRoot,C=CN";
        return checkDnKeyword(certDn);
    }

    public static void main(String[] args) {
        String[] array = new String[]{"C","CN","L","O","OU","ST","DC","DNQUALIFIER","GIVENNAME","INITIALS","SN","STREET","TITLE","TELEPHONENUMBER","UID"};
        String str = "STREET";
        boolean a = existStr(array, str);
        boolean b = existStr1(array, str);
        boolean c = existStr2(array, str);
        boolean d = existStr4();
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
    }
}

 

你可能感兴趣的:(学习笔记)