Métodos en Java: palíndromos, arrays, validaciones con expresiones regulares y más
Métodos en Java para trabajar con cadenas, arrays y validaciones
Método que comprueba si un texto es palíndromo
public static boolean esPalindromo(String texto) {
// Limpiar el texto: eliminar espacios, signos y convertir a minúsculas
String textoLimpio = texto.trim().toLowerCase().replaceAll("[ :.;,]", "");
// Comprobar si el texto es igual a su versión invertida
return textoLimpio.equals(new StringBuilder(textoLimpio).reverse().toString());
}
// Ejemplo de uso con un array de textos
String[] arrayTextos = {"Anita lava la tina", "Hola mundo", "A man a plan a canal Panama"};
boolean[] esPalindromo = new boolean[arrayTextos.length];
// Comprobar cada texto usando el método
for (int i = 0; i < arrayTextos.length; i++) {
esPalindromo[i] = esPalindromo(arrayTextos[i]);
}
// Mostrar resultados
for (int i = 0; i < arrayTextos.length; i++) {
System.out.println("\"" + arrayTextos[i] + "\" es palíndromo: " + esPalindromo[i]);
}
Método para invertir las palabras de cada texto en un array
public static String[] invertirPalabras(String[] textos) {
String[] textosInvertidos = new String[textos.length];
for (int i = 0; i < textos.length; i++) {
// Separar palabras y generar texto invertido
String[] palabras = textos[i].trim().split("[ :.;,]+");
StringBuilder textoInvertido = new StringBuilder();
for (String palabra : palabras) {
textoInvertido.append(new StringBuilder(palabra).reverse()).append(" ");
}
// Eliminar espacio final y guardar el resultado
textosInvertidos[i] = textoInvertido.toString().trim();
}
return textosInvertidos;
}
// Llamar al método para invertir palabras
String[] arrayTextosInvertidos = invertirPalabras(arrayTextos);
// Mostrar resultados
for (int i = 0; i < arrayTextos.length; i++) {
System.out.printf("Texto %d: \"%s\"\n", i + 1, arrayTextos[i]);
System.out.printf("Palabras invertidas: \"%s\"\n\n", arrayTextosInvertidos[i]);
}
Validar matrícula europea
public static boolean validarMatriculaEuropea_Exp(String matricula) {
return matricula.matches("^[0-9]{4}[A-Z]{3}$");
}
Generar número aleatorio
public static int generaNumeroAleatorio(int minimo, int maximo) {
int num = (int) (Math.random() * (minimo - (maximo + 1)) + (maximo + 1));
return num;
}
Rellenar matriz con números aleatorios
public static void rellenarMatrizAleatorios(int matriz[][], int minimo, int maximo) {
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[0].length; j++) {
matriz[i][j] = generaNumeroAleatorio(minimo, maximo);
}
}
}
Calcular factorial
public static int factorial(int num) {
int producto = num;
for (int i = num - 1; i > 0; i--) {
producto *= i;
}
return producto;
}
Ordenar un array
public static void ordenarArray(int[] array) {
Arrays.sort(array);
}
Buscar un valor en un array
public static int buscarEnArray(int[] array, int valor) {
for (int i = 0; i < array.length; i++) {
if (array[i] == valor) {
return i; // Retorna el índice de la primera ocurrencia
}
}
return -1; // Retorna -1 si no se encuentra el valor
}
Mínimo y máximo en un array
public static int minimoEnUnArray(int[] numeros) {
if (numeros == null) {
return -1;
} else {
int menor = numeros[0];
for (int i = 1; i < numeros.length; i++) {
if (numeros[i] < menor) {
menor = numeros[i];
}
}
return menor;
}
}
public static int maximoEnUnArray(int[] numeros) {
if (numeros == null) {
return -1;
} else {
int mayor = numeros[0];
for (int i = 1; i < numeros.length; i++) {
if (numeros[i] > mayor) {
mayor = numeros[i];
}
}
return mayor;
}
}
Validar IBAN
public static boolean esIBANValido(String iban) {
iban = iban.replaceAll("\\s+", "");
// Expresión regular para validar el formato IBAN
String regexIBAN = "^[A-Z]{2}\\d{2}[A-Z0-9]{1,30}$";
return iban.matches(regexIBAN);
}
Contar subcadenas
public static int contarSubcadena(String texto, String subcadena) {
int count = 0;
int index = 0;
while ((index = texto.indexOf(subcadena, index)) != -1) {
count++;
index++;
}
return count;
}
Invertir una cadena
public static String invertirString(String texto) { return new StringBuilder(texto).reverse().toString(); }
Eliminar espacios al inicio y al final
public static String eliminarEspacios(String texto) {
Pattern patron = Pattern.compile("^\\s+|\\s+$");
Matcher matcher = patron.matcher(texto);
return matcher.replaceAll("");
}
Obtener las primeras letras de cada palabra
public static String obtenerPrimerasLetras(String texto) {
StringBuilder resultado = new StringBuilder();
Pattern patron = Pattern.compile("\\b([a-zA-Z])");
Matcher matcher = patron.matcher(texto);
while (matcher.find()) {
resultado.append(matcher.group(1));
}
return resultado.toString();
}
Validar fecha
public static boolean validarFecha(String fecha) {
Pattern patron = Pattern.compile("^([0-2][0-9]|(3)[0-1])/(0[1-9]|1[0-2])/([12][0-9]{3})$");
Matcher matcher = patron.matcher(fecha);
return matcher.matches();
}
Validar contraseña segura
public static boolean validarContrasenaSegura(String contrasena) {
Pattern patron = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$");
Matcher matcher = patron.matcher(contrasena);
return matcher.matches();
}
Comprobar si un número es par o impar
public static boolean esNumeroPar(String numero) { Pattern patron = Pattern.compile("^[+-]?(0|[2468]\\d*)$"); Matcher matcher = patron.matcher(numero); return matcher.matches(); }
public static boolean esNumeroImpar(String numero) { Pattern patron = Pattern.compile("^[+-]?[13579]\\d*$"); Matcher matcher = patron.matcher(numero); return matcher.matches(); }
Contar dígitos
public static int contarDigitos(String numero) { Pattern patron = Pattern.compile("\\d"); Matcher matcher = patron.matcher(numero); int contador = 0; while (matcher.find()) { contador++; } return contador; }
Contar un carácter en una cadena
public static int contarCaracterEnString(String texto, char caracter) {
int count = 0;
for (int i = 0; i < texto.length(); i++) {
if (texto.charAt(i) == caracter) {
count++;
}
}
return count;
}