How do I ignore case when using startsWith and end

2020-03-01 02:58发布

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 cutInput starts with either "top" or "up" AND check if cutInput ends with either "left" or "right", all while being case-insensitive. Is this at all possible?

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.

3条回答
狗以群分
2楼-- · 2020-03-01 03:25

Like this:

aString.toUpperCase().startsWith("SOMETHING");
aString.toUpperCase().endsWith("SOMETHING");
查看更多
劳资没心,怎么记你
3楼-- · 2020-03-01 03:27

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

Here is my own version, based on 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()
    {
    }
}
查看更多
仙女界的扛把子
4楼-- · 2020-03-01 03:47

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.'"

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:

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.

查看更多
登录 后发表回答