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

送分小仙女□ 提交于 2019-11-30 17:00:01

Like this:

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

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()
    {
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!