Páginas

lunes, 18 de julio de 2011

Manejo De Cadenas En Java, Operaciones Con Palabras

Muchas de las operaciones básicas con cadenas (String's) cuando estamos aprendiendo a programar son las operaciones con las palabras en una cadena, problemas como: contar cuantas palabras tiene una cadena, eliminar la k-ésima palabra, invertir todas las palabras, etc. Ahora mostraremos los algoritmos de problemas clásicos resueltos de una forma nativa, ya que sabemos que Java tiene una infinidad de métodos en la clase String para manejar cadenas, pero haremos uso de las 3 mas básicas que son:
  • length() retorna el numero de caracteres de una cadena (String)
  • charAt(posicion) retorna un carácter (char) de la posicion en la cadena.
  • substring(inicio, fin) retorna una subcadena extraída de una cadena dada la posición de inicio y fin.
Con estos métodos básicos podemos hacer cualquier operación con cadenas (String's) ademas de ayuda podemos utilizar también el método trim() que elimina todos los espacios (carácter espacio) de adelante y del final de una cadena.

Bien, ahora entremos en tema, lo primero que tenemos que saber es como detectar una palabra, de la forma mas sencilla una cadena puede ser "Hola amigos espero que estén bien" que tiene 6 palabras, ademas observen que tiene 5 caracteres espacio, entonces podríamos decir que para detectar palabras nos enfocaremos en los espacios.

Contar Cuantas Palabras Tiene Una Cadena

Si tenemos la cadena "Hola amigos espero que estén bien" tiene 5 espacios entonces que tal si contamos cuantos espacios existen y le sumamos uno, esa podría ser una solución correcta, pero para otras operaciones mas complejas se aconseja adicionar o concatenar un espacio mas al final de la cadena teniendo asi "Hola amigos espero que estén bien " entonces una vez concatenado contaremos los espacios y serán 6, que representa 6 palabras, el código Java es el siguiente.

public static int contarPalabras(String cadena) {
    cadena += " ";
    int c = 0;
    for (int i = 0; i < cadena.length(); i++) {
        if (cadena.charAt(i) == ' ') {
            c++;
        }
    }
    return c;
}

Eliminar La K-ésima Palabra De Una Cadena

Primero necesitamos una nueva cadena donde se ira almacenando la cadena menos la palabra a eliminar, entonces lo que tenemos que hacer es también almacenar palabra por palabra en una variable y esto para concatenar a la nueva cadena pero menos una (la que tenemos que eliminar) logrando asi que estén en la nueva cadena todas las palabras menos una, para ello tambien necesitamos contar cada vez que encontremos una palabra, el código Java es el siguiente.

public static String eliminarPalabra(String cadena, int k) {
    cadena += " ";
    String nuevaCadena = "";
    int c = 0;
    String palabra = "";
    for (int i = 0; i < cadena.length(); i++) {
        palabra += cadena.charAt(i);
        if (cadena.charAt(i) == ' ') {
            c++;
            if (c != k) {
                nuevaCadena += palabra;
            }
            palabra = "";
        }
    }
    return nuevaCadena.trim();
}

Invertir Las Palabras De Una Cadena

El truco para invertir una cadena es en la concatenación, la concatenación por izquierda, es decir si nosotros tenemos la cadena "abc" y hacemos la siguiente operación 'x' + "abc", tenemos "xabc" y así si extraemos carácter por carácter y lo concatenamos por izquierda ya tenemos la cadena invertida, lo mismo hay que hacer pero palabra por palabra, detectando palabras y almacenándolas inversamente y luego recien concatenar la palabra a la nueva cadena, el código Java es el siguiente.

public static String invertirPalabras(String cadena) {
    cadena += " ";
    String palabra = "";
    String nuevaCadena = "";
    for (int i = 0; i < cadena.length(); i++) {
        palabra = cadena.charAt(i) + palabra;
        if (cadena.charAt(i) == ' ') {
            nuevaCadena += palabra;
            palabra = "";
        }
    }
    return nuevaCadena.trim();
}

Como podemos ver también se utilizo la función trim() para eliminar los espacios sobrantes en las cadenas resultantes.


Nota. Este Post como todos del blog son actualizados constantemente, se añadirán mas funciones con palabras, para enterarte cuando hazte fan de la pagina de facebook y si quieres información basica de lo que son cadenas y conceptos de sintaxis en Java, descarga las diapositivas del curso Java.

    32 comentarios:

    1. muy buenos los aportes sobre Java..

      saludos y excelente blog..

      ResponderEliminar
    2. Escribo en este foro para pedir ayuda en un script Java que me permita resolver el siguinete problema de manejo de strings:

      Variable [texto]

      Si el string: [href="http://en.wikipedia.org/wiki/"] existe en la variable [texto] y si [href="http://en.wikipedia.org/wiki/] + los 5 caracteres siguientes es diferente a [href="http://en.wikipedia.org/wiki/File]

      Entonces: Remplaza todo lo que esta a la derecha de [href="] hasta ["] por [#]

      Si no: No hacer nada.

      El script tiene que hacer eso hasta que recorra toda la variable [texto].


      Saludos y gracias de ante mano por la buena voluntad

      ResponderEliminar
    3. QUE BUENA GRACIAS AHORA YA ENTIENDO

      ResponderEliminar
    4. amigo el metodo contar palabras tiene un error ya que cuando se presiona varias veces la barra espaciadora que son espacios obviamente, lo toma como palabras es decir
      ejemplo: lo que esciba entre comilla va ser el texto

      "hola como estan" --->aki me muestra que hay 3 palabras eso ta bn

      2)
      "hola mundo "---> aki me muestra como 40 palabras si puedes mejorarlo bn ya que ese codigo o metodo que hizo no es conveniente

      ResponderEliminar
      Respuestas
      1. see ejta mal ese ejercicio resolvelo no es complejo

        Eliminar
      2. bueno :) te paso el codigo correcto aunq se puede optimizar:
        public String contarPal( String cad){
        String A="";
        int c=0;
        for (int i = 0; i <cad.length(); i++) {
        if (cad.charAt(i)!=' '){
        A=A+cad.charAt(i);
        }else if (A!=""){
        c++;
        A="";
        }
        }
        if (A!=""){
        c++;
        }
        return A=Integer.toString(c);
        }

        Eliminar
    5. ta weno pero faltan mas ejercicios

      ResponderEliminar
    6. For such kind of information, be always in contact with us through our blogs. To locate the reliable way to obtain assist to create customer checklist in QB desktop, QuickBooks online and QuickBooks Payroll Support Phone Number

      ResponderEliminar
    7. We're going to also provide you with the figure of your respective budget which you can be in the near future from now. This is only possible with QuickBooks Enterprise Support Number

      ResponderEliminar
    8. The payroll service functions within the QuickBooks program, so that you would not have to enter the info twice. Moreover, you can always avail specialist help by connecting yourself aided by the QuickBooks Payroll Tech Support Phone Number Team. They have been always readily available for your assistance regarding anything within the software.

      ResponderEliminar
    9. The guide might have helped you understand QuickBooks Support Phone Number corruption and methods to resolve it accordingly. If you would like gain more knowledge on file corruption or any other accounting

      ResponderEliminar
    10. QuickBooks is rated business accounting software and the minute query or issue troubling you do not panic, call the QuickBooks Technical Support Phone Number. The Intuit certified technician called Proadviors can assist & help you to sort out any errors , problem .

      ResponderEliminar
    11. Each one of these issues mentioned above are a couple of types of what kind of tech glitches users may face. QuickBooks Enterprise help is the only solution when it comes to selection of issues. So, contact with our QuickBooks support team with the QuickBooks Enterprise customer support number to enjoy all the latest plans and services made available from us globally. Dial our QuickBooks Enterprise Technical Support to get an immediate QuickBooks help.

      ResponderEliminar
    12. web browser setting and system time and date setting you can just call us at QuickBooks 2019 Support PHone Number for instant assistance in QB issues.

      ResponderEliminar
    13. Stay calm when you are getting any trouble using payroll. You just need to make one call to solve your trouble by using the Intuit Certified Pro Advisor. Dial QuickBooks Payroll Help Phone Number USA for effective solutions for basic, enhanced and intuit full service payroll. Whether the issue relates to the tax table update, service server, payroll processing timing, Intuit server unable to respond, or QuickBooks update issues; we assure you to deliver precise technical assist with you on time.

      ResponderEliminar
    14. Your QuickBooks Support Phone Number team is just just one tap away, dial our QuickBooks Support contact number and experience our best hassle-free tech support team.

      ResponderEliminar
    15. QuickBooks Enterprise Tech Support Number offered at qbenterprisesupport.com are created to give you tech assistance par excellence for just about any glitches or hiccups you may possibly possibly run into during working with your QuickBooks Enterprise.

      ResponderEliminar
    16. Este comentario ha sido eliminado por el autor.

      ResponderEliminar
    17. QuickBooks has completely transformed the way people used to operate their business earlier. To get familiar with it, you should welcome this positive change. Supervisors at QuickBooks Tech Support Number have trained all of their executives to combat the issues in this software.

      ResponderEliminar
    18. We make sure that your calls don't get bounced. Should your calls are failing woefully to connect with us at QuickBooks Support Phone Number, then you can certainly also join all of us by dropping a contact without feeling shy. Our customer service support will continue to be available even in the wee hours.

      ResponderEliminar
    19. Utilizing the introduction of modern tools and approaches to QuickBooks, you can test new techniques to carry out various business activities. Basically, this has automated several tasks that have been being done manually for a long time. There are lots of versions of QuickBooks Support Phone Nmber and each one has a unique features.

      ResponderEliminar
    20. Sometimes you do not forecast the precise budget. We've got experienced individuals to offer the figure. We're going to also give you the figure of your respective budget which you yourself can get in the future from now. This is only possible with Support For QuickBooks.

      ResponderEliminar
    21. QuickBooks accounting software is the most effective accounting software commonly abbreviated by the name QB used to manage and organize all finance-related information properly. Reliability, accuracy, and certainly increase its demand among businessmen and entrepreneurs. It really is a great money management system for numerous companies all over the world. When using it, a suitable and effective QuickBooks help is necessary by either you or your QuickBooks online accountant for the best out of this software. Make contact with our independent AccountWizy Quickbooks customer care to get the best advice from our United States based Certified ProAdvisors to be able to fix business or accounting queries as well as QuickBooks Technical Support Number. Our third party independent AccountWizy Quickbooks support phone number and our experts are 24/7 active to offer Quickbooks customer service for its products.

      ResponderEliminar
    22. For many such situations, go ahead and contact us anytime from anywhere at QuickBooks Support Number USA. QuickBooks is a cleverly designed accounting software to avoid the most odds of error.

      ResponderEliminar
    23. There are numerous payroll options made available due to the online kind of QuickBooks varying upon the need of accounting professionals and subscription plans. QuickBooks Support as well provides all possible help with the users to utilize it optimally. An individual who keeps connection with experts is able to realize about the latest updates.

      ResponderEliminar
    24. It’s extraordinary for organizations which report using one basis & record assesses yet another.Search to the chart of accounts really is easy to control with added search bar right into the chart of accounts. For better information, you could call at QuickBooks Enterprise Solutions Support.

      ResponderEliminar
    25. We make sure your calls do not get bounced. Should your calls are failing to interact with us at QuickBooks customer Support Number, then you can certainly also join our team by dropping a message without feeling shy. Our customer care support will continue to be available even at the wee hours.

      ResponderEliminar
    26. So now you are well conscious of advantages of QuickBooks online payroll in your company accounting but as this premium software contains enhanced functions to help you along with your accounting task to complete, so you might face some technical errors while using QuickBooks Payroll Support Number solution.

      ResponderEliminar
    27. you currently scratching your head and stuck together with your QuickBooks related issues, you'll be only one click definately not our expert tech support team for your QuickBooks Tech Support Phone Number related issues.

      ResponderEliminar
    28. You can actually resolve this error by using the below troubleshooting steps you can simply contact our QuickBooks Support Phone Number available at.You should run QuickBooks Tech Support Number print and pdf repair tool to ascertain and fix the errors in printer settings before you start the troubleshooting.

      ResponderEliminar
    29. If you prefer more info you can get touch with trained experts via Quickbooks Desktop support Customer services. This software has made it popular among its users. If you want help customer support to master customization of invoice or add an additional benefit to your invoice. If you would like to learn How To Troubleshoot QuickBooks Error 9999, you can continue reading this blog.

      ResponderEliminar

    Deja tu comentario, agradecimiento, sugerencia o critica.