在Java中使用startsWith和endsWith时如何忽略大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26794275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:17:51  来源:igfitidea点击:

How do I ignore case when using startsWith and endsWith in Java?

javastringcase-insensitivestartswithends-with

提问by Matao Gearsky

Here's my code:

这是我的代码:

public static void rightSel(Scanner scanner,char t)
{
  /*if (!stopping)*/System.out.print(": ");
    if (scanner.hasNextLine())
    {
     String orInput = scanner.nextLine;
        if (orInput.equalsIgnoreCase("help")
        {
            System.out.println("The following commands are available:");
            System.out.println("    'help'      : displays this menu");
            System.out.println("    'stop'      : stops the program");
            System.out.println("    'topleft'   : makes right triangle alligned left and to the top");
            System.out.println("    'topright'  : makes right triangle alligned right and to the top");
            System.out.println("    'botright'  : makes right triangle alligned right and to the bottom");
            System.out.println("    'botleft'   : makes right triangle alligned left and to the bottom");
        System.out.println("To continue, enter one of the above commands.");
     }//help menu
     else if (orInput.equalsIgnoreCase("stop")
     {
        System.out.println("Stopping the program...");
            stopping    = true;
     }//stop command
     else
     {
        String rawInput = orInput;
        String cutInput = rawInput.trim();
        if (

I'd like to allow the user some leeway as to how they can enter the commands, things like: Top Right, top-right, TOPRIGHT, upper left, etc. To that end, I'm trying to, at that last if (, check if cutInputstarts with either "top" or "up" AND check if cutInputends with either "left" or "right", all while being case-insensitive. Is this at all possible?

我想允许用户在如何输入命令方面有一些回旋余地,例如:右上角、右上角、TOPRIGHT、左上角等。为此,我试图,最后if (,检查是否cutInput以“top”或“up”开头并检查是否cutInput以“left”或“right”结尾,同时不区分大小写。这是可能吗?

The end goal of this is to allow the user to, in one line of input, pick from one of four orientations of a triangle. This was the best way I could think of to do that, but I'm still quite new to programming in general and might be over complicating things. If I am, and it turns there's a simpler way, please let me know.

这样做的最终目标是允许用户在一行输入中从三角形的四个方向之一中进行选择。这是我能想到的最好的方法,但我对编程仍然很陌生,可能会使事情变得过于复杂。如果我是,并且有更简单的方法,请告诉我。

采纳答案by óscar López

Like this:

像这样:

aString.toUpperCase().startsWith("SOMETHING");
aString.toUpperCase().endsWith("SOMETHING");

回答by Gili

The accepted answer is wrong. If you look at the implementation of String.equalsIgnoreCase()you will discover that you need to compare bothlowercase and uppercase versions of the Strings before you can conclusively return false.

接受的答案是错误的。如果你看的实施String.equalsIgnoreCase(),你会发现,你需要比较两个小写字母和字符串的大写版本中,你最终能回来之前false

Here is my own version, based on http://www.java2s.com/Code/Java/Data-Type/CaseinsensitivecheckifaStringstartswithaspecifiedprefix.htm:

这是我自己的版本,基于http://www.java2s.com/Code/Java/Data-Type/CaseinsensitivecheckifaStringstartswithaspecifiedprefix.htm

/**
 * String helper functions.
 *
 * @author Gili Tzabari
 */
public final class Strings
{
    /**
     * @param str    a String
     * @param prefix a prefix
     * @return true if {@code start} starts with {@code prefix}, disregarding case sensitivity
     */
    public static boolean startsWithIgnoreCase(String str, String prefix)
    {
        return str.regionMatches(true, 0, prefix, 0, prefix.length());
    }

    public static boolean endsWithIgnoreCase(String str, String suffix)
    {
        int suffixLength = suffix.length();
        return str.regionMatches(true, str.length() - suffixLength, suffix, 0, suffixLength);
    }

    /**
     * Prevent construction.
     */
    private Strings()
    {
    }
}

回答by William McDowell

I was doing an exercise in my book and the exercise said, "Make a method that tests to see if the end of a string ends with 'ger.' Write the code to where it tests for any combination of upper-case and lower-case letters in the phrase 'ger.'"

我在我的书中做一个练习,练习说:“制作一个方法来测试字符串的结尾是否以 'ger' 结尾。将代码写入测试短语 'ger' 中大写和小写字母的任意组合的位置。

So, basically, it asked me to test for a phrase within a string and ignore the case so it doesn't matter if letters in "ger" are upper or lower-case. Here is my solution:

因此,基本上,它要求我测试字符串中的短语并忽略大小写,因此“ger”中的字母是大写还是小写都没有关系。这是我的解决方案:

package exercises;

import javax.swing.JOptionPane;

public class exercises
{
    public static void main(String[] args)
    {
        String input, message = "enter a string. It will"
                                + " be tested to see if it "
                                + "ends with 'ger' at the end.";



    input = JOptionPane.showInputDialog(message);

    boolean yesNo = ends(input);

    if(yesNo)
        JOptionPane.showMessageDialog(null, "yes, \"ger\" is there");
    else
        JOptionPane.showMessageDialog(null, "\"ger\" is not there");
}

public static boolean ends(String str)
{
    String input = str.toLowerCase();

    if(input.endsWith("ger"))
        return true;
    else 
        return false;
}

}

}

as you can see from the code, I simply converted the string that a user would input to all lower-case. It would not matter if every letter was alternating between lower and upper-case because I negated that.

从代码中可以看出,我只是将用户输入的字符串全部转换为小写。如果每个字母都在小写和大写之间交替并不重要,因为我否定了这一点。