usar una posicion endswith como caracter cadena buscar java string case-insensitive startswith ends-with

una - ¿Cómo ignoro mayúsculas y minúsculas cuando utilizo startsWith y endsWith en Java?



startswith java (3)

Estaba haciendo un ejercicio en mi libro y el ejercicio decía: "Haz un método que pruebe para ver si el final de una cuerda termina con ''ger''. Escriba el código donde compruebe cualquier combinación de letras mayúsculas y minúsculas en la frase "ger".

Entonces, básicamente, me pidió que probara una frase dentro de una cadena e ignorara el caso, por lo que no importa si las letras en "ger" son mayúsculas o minúsculas. Aquí está mi solución:

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; }

}

Como puede ver en el código, simplemente convertí la cadena que un usuario ingresaría en minúsculas. No importaría si cada letra alternara entre mayúscula y minúscula porque lo negué.

Esta pregunta ya tiene una respuesta aquí:

Aquí está mi código:

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 (

Me gustaría permitirle al usuario un margen de maniobra sobre cómo pueden ingresar los comandos, cosas como: Superior derecha, superior derecha, TOPRIGHT, superior izquierda, etc. Con ese fin, estoy intentando, al final, if ( , compruebe si cutInput comienza con "arriba" o "arriba" Y verifique si cutInput termina con "izquierda" o "derecha", todo esto sin distinguir mayúsculas y minúsculas. ¿Es esto posible?

El objetivo final de esto es permitir al usuario, en una línea de entrada, elegir entre una de las cuatro orientaciones de un triángulo. Esta era la mejor manera en la que podía pensar para hacer eso, pero todavía soy bastante nuevo en la programación en general y podría estar complicando las cosas. Si lo estoy, y resulta que hay una manera más simple, por favor hágamelo saber.


La respuesta aceptada es incorrecta. Si observa la implementación de String.equalsIgnoreCase() , descubrirá que necesita comparar las versiones en minúsculas y mayúsculas de las cadenas antes de poder devolver de forma concluyente el valor false .

Aquí está mi propia versión, basada en 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() { } }


Me gusta esto:

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