SERVLET PROGRAM TO REMOVE THE GIVEN CHARACTER FROM ALL OCCURENCES OF A GIVEN STRING

 INDEX.HTML

<html>

        <body>

             <form method="get" action="charremoval">

            Enter any string:<input style="font-size:25px;" type="text"  name="s1"><br>

            Enter the character to remove from the string:<input style="font-size:25px;" type="text" name="c1"><br>

            <input type="submit" value="click me">

        </form>

         </body>

</html>Top of FormBottom of Form

charremoval.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class charremoval extends HttpServlet {

   protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {

            out.println("<!DOCTYPE html>");

            out.println("<html>");

            out.println("<head>");

            out.println("<title>Servlet charremoval</title>");           

            out.println("</head>");

            out.println("<body>");

            out.println("<h1>Servlet charremoval at " + request.getContextPath() + "</h1>");

            out.println("</body>");

            out.println("</html>");

        }

    }  

    @Override

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

         response.setContentType("text/html;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {

            String s;

            s=request.getParameter("s1");

             out.println("<b><h2>Given string is "+s+"</b></h2>");

             String c;

            c=request.getParameter("c1");

            out.println("<b><h2>Character to Remove from the  string is "+c+"</b></h2>");

            char c1=c.charAt(0);

           int l=s.length();

            int i;

            String[] myarray = new String[l];

            for(i=0;i<=l-1;i++){

                char cha=s.charAt(i);

                 if (c1==cha){

                out.println("<b><h2>found the char at "+i+"</b></h2>");

                myarray[i]=" ";

                                    } 

                else{

                    myarray[i]=Character.toString(cha);

                }

              }

             int len = myarray.length;

             StringBuffer sb = new StringBuffer();

             for (i = 0; i < len; i++) {

                 if (myarray[i] != " ") {

                   sb.append(myarray[i]);

                 }

             }

             out.println("<b><h2>Given String After Removal is "+sb.toString()+"</b></h2>" );

             }

    }

}

OUTPUT:






No comments:

Post a Comment