How do I ignore case when using startsWith and endsWith in Java? [duplicate]
Asked Answered
N

3

60

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.

Newburg answered 7/11, 2014 at 4:51 Comment(1)
Use command.toLowerCase().startsWith("up") and command.toLowerCase().endsWith("right").Porte
M
90

Like this:

aString.toUpperCase().startsWith("SOMETHING");
aString.toUpperCase().endsWith("SOMETHING");
Marxismleninism answered 7/11, 2014 at 4:55 Comment(6)
Will .toUpperCase() work even if the string contains non-alphabetic characters? Also, do you know if these can be combined in a conditional using logic(al?) operators?Newburg
@MataoGearsky It'll work, of course. The non-alphabetic characters will simply be ignored by toUpperCase(). And sure enough, the above can be combined with logical operators (and why not? they're just boolean expressions.)Trafficator
This 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. See my answer at https://mcmap.net/q/160540/-how-do-i-ignore-case-when-using-startswith-and-endswith-in-java-duplicate.Bertsche
And its performance is not optimal. What if your aString is huge?Anstice
Will not work for other locales. "edit".toUpperCase() is "EDİT" in Turkish (Note the dot on the capital i) So "editThis".toUpperCase().startsWith("EDIT") returns false with a turkish locale.Countersubject
Ma non è vero! ~MichaelVisigoth
B
52

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()
    {
    }
}
Bertsche answered 14/8, 2016 at 23:34 Comment(11)
Is that only because of the Georgian alphabet?Tol
@bphilipnyc Correct. That is one example mentioned by the String source-code, but we have no idea whether it is the only one. Better safe than sorry.Bertsche
In addition this method avoids lowercasing and copying parts of the string that would never be checked.Pegmatite
Side note: Spring Framework aligns with Gili's answer, too: github.com/spring-projects/spring-framework/blob/master/…Particularity
This is a concrete example for why we need to compare both lowercase and uppercase versions : https://mcmap.net/q/160541/-understanding-logic-in-caseinsensitivecomparatorNathanialnathaniel
Note: please format it as Java. It's nor C++ or C#.Dehorn
@Aleksander Lech as far as I can see it's formatted just fine. What issue do you have with it?Bertsche
@Bertsche in Java we don't put a new line before the opening curly bracket like we do for C++ or C# languages.Dehorn
@AleksanderLech I've been programming in Java for over 20 years. Similar to the tab vs space debate, different people/companies use whatever formatting they see fit. My particular standard involves a newline before opening curly bracket. I do this because I feel the resulting code is more readable (the open/close brackets line up vertically). To each his own.Bertsche
Well I have never seen such a formatting in Java despite I only have 15 years experience here. I advise you though to check the old java conventions document and check the JDK classes formatting :)Dehorn
The accepted answer is correct if the user is comparing to strings like in their example. If they want to compare to character sets beyond their example, then maybe a more complex solution like yours would be appropriate.Nirvana
F
1

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.

Finny answered 6/9, 2017 at 23:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.