【问题标题】:Ignoring upper case and lower case in Java忽略Java中的大写和小写
【发布时间】:2015-01-15 19:25:44
【问题描述】:

我想知道如何在我的方法中让用户输入的内容忽略大小写:

public static void findPatient() {
    if (myPatientList.getNumPatients() == 0) {
        System.out.println("No patient information is stored.");
    }
    else {
        System.out.print("Enter part of the patient name: ");
        String name = sc.next();
        sc.nextLine();
        System.out.print(myPatientList.showPatients(name));
    }
}

【问题讨论】:

标签: java string uppercase lowercase


【解决方案1】:

您必须在输入和您尝试与之匹配的字符串上都使用 String 方法 .toLowerCase().toUpperCase()

例子:

public static void findPatient() {
    System.out.print("Enter part of the patient name: ");
    String name = sc.nextLine();

    System.out.print(myPatientList.showPatients(name));
}

//the other class
ArrayList<String> patientList;

public void showPatients(String name) {
    boolean match = false;

    for(String matchingname : patientList) {
        if (matchingname.toLowerCase().contains(name.toLowerCase())) {
            match = true;
        }
    }
}

【讨论】:

    【解决方案2】:

    使用String#toLowerCase()String#equalsIgnoreCase() 方法

    一些例子:

        String abc    = "Abc".toLowerCase();
        boolean isAbc = "Abc".equalsIgnoreCase("ABC");
    

    【讨论】:

      【解决方案3】:

      .equalsIgnoreCase() 方法应该对此有所帮助。

      【讨论】:

        【解决方案4】:

        使用 String 类的 toUpperCase() 或 toLowerCase() 方法。

        【讨论】:

          【解决方案5】:

          在处理数据时忽略大小写,而不是在检索/存储数据时。 如果您想以小写形式存储所有内容,请使用String#toLowerCase,以大写形式使用String#toUpperCase

          那么当你必须真正对待它时,你可能会使用不合时宜的方法,比如String#equalsIgnoreCase(java.lang.String)。如果 Java API 中没有任何东西可以满足您的需求,那么您将不得不编写自己的逻辑。

          【讨论】:

            【解决方案6】:

            我也尝试了所有发布的代码,直到我发现了这个

            if(math.toLowerCase(Locale.ENGLISH));
            

            在这里,用户输入的任何字符都将转换为小写。

            【讨论】:

            • 这里怎么做?
            猜你喜欢
            • 2021-12-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-08-24
            • 2017-02-25
            • 1970-01-01
            相关资源
            最近更新 更多