首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Java中使用startsWith和endsWith时如何忽略大小写?

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

Stack Overflow用户
提问于 2014-11-07 12:51:17
回答 3查看 67.6K关注 0票数 43

下面是我的代码:

代码语言:javascript
运行
复制
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 (

我想给用户一些回旋余地,让他们如何输入命令,比如:右上,右上,拓扑,左上等等。为此,我试图在最后一个if (检查cutInput是否以" Top“或"up”开头,并检查cutInput是否以" left“或" Right”结尾,同时不区分大小写。这有可能吗?

这样做的最终目标是允许用户在一行输入中从三角形的四个方向中选择一个。这是我能想到的最好的方式,但我对编程总体上还是相当陌生的,可能会把事情搞得过于复杂。如果是的话,有更简单的方法,请让我知道。

EN

Stack Overflow用户

发布于 2016-08-15 07:34:54

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

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

代码语言:javascript
运行
复制
/**
 * 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()
    {
    }
}
票数 37
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26794275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档