Saltar al contenido

comparar string a int en el ejemplo de código java

Nuestro team de trabajo ha estado mucho tiempo investigando para dar resolución a tu duda, te compartimos la soluciones así que nuestro deseo es servirte de mucha ayuda.

Ejemplo 1: comparar string entero java

/**
    * Similar to compareTo method But compareTo doesn't return correct result for string+integer strings something like `A11` and `A9`
*/privateintnewCompareTo(String comp1,String comp2)// If any value has 0 length it means other value is biggerif(comp1.length()==0)if(comp2.length()==0)return0;return-1;elseif(comp2.length()==0)return1;if(TextUtils.isDigitsOnly(comp1))int val1 =Integer.parseInt(comp1);if(TextUtils.isDigitsOnly(comp2))int val2 =Integer.parseInt(comp2);returnInteger.compare(val1, val2);elsereturn comp1.compareTo(comp2);elseint minVal =Math.min(comp1.length(), comp2.length()), sameCount =0;// Loop through two strings and check how many strings are samefor(int i =0;i < minVal;i++)char leftVal = comp1.charAt(i), rightVal = comp2.charAt(i);if(leftVal == rightVal)
        sameCount++;elsebreak;if(sameCount ==0)return comp1.compareTo(comp2);elseString newStr1 = comp1.substring(sameCount), newStr2 = comp2.substring(sameCount);if(TextUtils.isDigitsOnly(newStr1)&&TextUtils.isDigitsOnly(newStr2))returnInteger.compare(Integer.parseInt(newStr1),Integer.parseInt(newStr2));elsereturn comp1.compareTo(comp2);

Ejemplo 2: string entero comparar java

num ==Integer.parseInt(str) is going tofaster than str.equals(""+ num)

str.equals(""+ num) will first convert num tostring which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finallydo the string comparison. String comparison in thiscase will be another O(n)- n being the number of digits in the number. So in all ~3*O(n)

num ==Integer.parseInt(str) will convert the string tointeger which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1).So just ~1*O(n)To summarize both are O(n)- but str.equals(""+ num) has a higher constant and so is slower.

Sección de Reseñas y Valoraciones

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *