日期:2014-05-20  浏览次数:20799 次

如何遍历一个字符串中是否存在另一个字符串
如:“I1I2I3”这个字符串,有个子字符串“I1I3”,这个用contains判断是不存在在那个字符串中的
有什么方法可以判断I1I3是存在那个字符串中的。既只要I1I2I3这个字符串只要有I1I3就可以了,

------解决方案--------------------
把字串逐个比较呀:
Java code

    public static void main(String[] args) {
        System.out.println(charContains("I1I2I3", "I1I3"));
    }

    public static boolean charContains(String s, String sub) {
        if (s == null || sub == null)
            return false;

        for (int i = 0; i < sub.length(); i++) {
            boolean contains = false;
            char c = sub.charAt(i);
            for (int j = 0; j < s.length(); j++) {
                if (c == s.charAt(j)) {
                    contains = true;
                    break;
                }
            }
            if (!contains)
                return false;
        }

        return true;
    }