【问题标题】:How do I ignore case when using startsWith and endsWith in Java? [duplicate]在Java中使用startsWith和endsWith时如何忽略大小写? [复制]
【发布时间】:2014-11-07 04:51:17
【问题描述】:

这是我的代码:

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 (

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

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

【问题讨论】:

  • 使用command.toLowerCase().startsWith("up")command.toLowerCase().endsWith("right")

标签: java string case-insensitive startswith ends-with


【解决方案1】:

像这样:

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

【讨论】:

  • 即使字符串包含非字母字符,.toUpperCase() 也能正常工作吗?另外,您知道这些是否可以使用逻辑(al?)运算符在条件中组合?
  • @MataoGearsky 当然可以。 toUpperCase() 将简单地忽略非字母字符。果然,以上内容可以与逻辑运算符结合使用(为什么不呢?它们只是布尔表达式。)
  • 这个答案是错误的。如果您查看String.equalsIgnoreCase() 的实现,您会发现您需要比较字符串的小写和大写版本,然后才能最终返回false。在stackoverflow.com/a/38947571/14731 上查看我的回答。
  • 而且它的性能不是最优的。如果您的aString 很大怎么办?
【解决方案2】:

接受的答案是错误的。如果您查看 String.equalsIgnoreCase() 的实现,您会发现您需要比较 字符串的小写和大写版本,然后才能最终返回 false

这是我自己的版本,基于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()
    {
    }
}

【讨论】:

  • 仅仅是因为格鲁吉亚字母吗?
  • @bphilipnyc 正确。这是String 源代码中提到的一个例子,但我们不知道它是否是唯一的一个。安全总比后悔好。
  • 此外,此方法避免小写和复制永远不会检查的字符串部分。
  • 旁注:Spring Framework 也符合 Gili 的回答:github.com/spring-projects/spring-framework/blob/master/…
  • @AleksanderLech 我用 Java 编程已经 20 多年了。类似于标签与空间的辩论,不同的人/公司使用他们认为合适的任何格式。我的特定标准涉及在打开大括号之前换行。我这样做是因为我觉得生成的代码更具可读性(开/关括号垂直排列)。各有各的。
【解决方案3】:

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

因此,基本上,它要求我测试字符串中的短语并忽略大小写,因此“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;
}

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多