← All resources

Write a program to input a string and delete multiple spaces. Also delete the common words

import java.io.*;
public class String_extract
{
    public String dexspace(String s)
    {
        int i, l;
        char c1, c2;;
        String ns="";
        s = s.trim()+' ';
        l = s.length();
        for(i=0;i<l-1;i++)
        {
            c1 = s.charAt(i);
            c2 = s.charAt(i+1);
            if(c1!=' ')
            ns+=c1;
            else if(c1==' '&&c2!=' ')
            ns+=' ';
        }
        return ns;
    }
    int count(String s)
    {
        s = s.trim();
        int i, c=0;
        for(i=0;i<s.length();i++)
        {
            if(s.charAt(i)==' ')
            c++;
        }
        return (c+1);
    }
    public String delcom_word(String s)
    {
        s = s+' ';
        int l = s.length(), c=0, i, j;
        String w="", s2[] = new String[count(s)];       //Making string array based on number of words
        String ns="";
        char ch;
        for(i=0;i<l;i++)
        {
            ch = s.charAt(i);
            if(ch!=' ')
            w = w+ch;
            else
            {
                s2[c] = w;
                w="";
                c++;
            }
        }
        for(i=0;i<s2.length;i++)
        {
            for(j=i+1;j<s2.length;j++)
            {
                if(s2[i].equalsIgnoreCase(s2[j]))
                s2[j]="";
            }
        }
        for(i=0;i<s2.length;i++)
        {
            if(s2[i]!="")
            ns = ns+s2[i]+' ';
        }
        return ns.trim();
    }
    public void main()throws IOException
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        String s, w="";
        char c1, c2;
        int i, l;
        System.out.println("Enter a string:");
        s = r.readLine();
        s = dexspace(s);
        System.out.println("Output without extra spaces: "+s);
        s = delcom_word(s);
        System.out.println("Output without common words: "+s);
    }
}
Enter a string:
This    is   a   sample    string    which   is used to show    a  an answer
Output without extra spaces: This is a sample string which is used to show a an answer
Output without common words: This is a sample string which used to show an answer