美文网首页java学习笔记IT技术篇
java判断一个字符串中的所有字母是否包含在另一个字符串里面

java判断一个字符串中的所有字母是否包含在另一个字符串里面

作者: 菜菜___ | 来源:发表于2019-10-12 10:41 被阅读0次

    题目:
    有两个字符串由不同的字母组成,一长一短,长的为A短的为B。设计一个算法,如果所有在B中出现的字符都在A中出现,则返回true,否则返回false。
    使用indexOf()和charAt()两种方法进行判断:

    package com.company;
    
    import java.util.Scanner;
    
    /**
     * 判断一个字符串的所有字母是否包含在另一个字符串中
     */
    public class Test {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("请输入两个字符串:");
            Scanner sc = new Scanner(System.in);
            String i = sc.nextLine();
            String j = sc.nextLine();
    //      System.out.println("字符串比较结果为:"+checkFun(i, j));
            System.out.println("字符串比较结果为:" + checkFun1(i, j));
        }
    
        // 方法1  indexOf
        private static boolean checkFun(String i, String j) {
            String a;
            String b;
            if (i.length() > j.length()) {
                a = i;
                b = j;
            } else {
                a = j;
                b = i;
            }
            int count = 0;
    
            for (int bi = 0; bi < b.length(); bi++) {
                String[] bArr = b.split("");
                if (a.indexOf(bArr[bi]) != -1) {
                    count++;
                } else {
                    break;
                }
            }
            if (b.length() == count) {
                return true;
            } else {
                return false;
            }
    
        }
    
        // 方法2  charAt
        private static boolean checkFun1(String i, String j) {
            String a;
            String b;
            if (i.length() > j.length()) {
                a = i;
                b = j;
            } else {
                a = j;
                b = i;
            }
            int count = 0;
    
            for (int bj = 0; bj < b.length(); bj++) {
                for (int ai = 0; ai < a.length(); ai++) {
                    if (a.charAt(ai) == b.charAt(bj)) {
                        count++;
                        break;
                    }
                }
            }
            if (count == b.length()) {
                return true;
            } else {
                return false;
            }
        }
    }
    

    运行结果:

    请输入两个字符串:
    sdjfksbsdssbds
    swednd
    字符串比较结果为:false
    
    请输入两个字符串:
    qwert
    weee
    字符串比较结果为:true
    

    其中方法二中两层for循环遍历的时候记得拿短的字符串去与长的字符串进行比较,即第一层for循环为短的字符串。
    原文作者技术博客:https://www.jianshu.com/u/ac4daaeecdfe

    相关文章

      网友评论

        本文标题:java判断一个字符串中的所有字母是否包含在另一个字符串里面

        本文链接:https://www.haomeiwen.com/subject/vdpnuctx.html