在Java中忽略大写和小写

问题描述 投票:2回答:6

我想知道如何在我的方法中使用任何用户输入来忽略大小写:

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
6个回答
6
投票

你必须在输入和你想要匹配的字符串上使用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(matchingname : patientList) {
        if (matchingname.toLowerCase.contains(name.toLowerCase())) {
            match = true;
        }
    }
}

7
投票

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

一些例子:

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

2
投票

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


0
投票

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


0
投票

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

然后,当你必须真正对待它时,你可以使用弓箭方法,如String#equalsIgnoreCase(java.lang.String)。如果Java API中不存在满足您需求的任何内容,那么您将必须编写自己的逻辑。


0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.