Search code examples
javastringtrim

Java program for advanced trimming of String


ORIGINAL QUESTION IS----Write a program in java to input a sentence which ends only with ! or ? .each word in the sentence is separated by single blank space. convert the sentence into upper case and remove extra blank spaces so that each word is separated by a single blank space only. Print message for invalid input.

I have written an answer this but cant made it. here's my code:

package OMG;
import java.util.Scanner;
public class Trimmer_new 
{
    String Trim(String s)
    {
        s=s.trim();
        String ans="";
        int k=0;
        s=s+" ";
        for(int i=1;i<=s.length();i++)
        {
            if(s.charAt(k)!= ' ') 
            {
                char g=s.charAt(k);
                ans=ans+g;
                k++;
            }
            else
            {
                while(s.charAt(k)==' ')
                {
                    k++;                    
                }
                ans=ans+" ";
                k++;
            }
        }
        ans.trim();
        return ans;
    }
    public static void main(String[]args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a sentance ending only with '!' or '?': ");
        String a=sc.next();  
        if(a.endsWith("!")==true||a.endsWith("?")==false)           
        {
            Trimmer_new ob= new Trimmer_new();
            System.out.println("Trimmed sentence: "+ob.Trim(a));
        }  
        else
        {
            System.out.println("error");
        }
        sc.close();
    }
}

But at time of running it throws an exception:

Please click here to see

Can anyone provide me with a better and clean code??

(I am doing this in Eclipse IDE)


Solution

  • there are two issues. first you are never making check while incrementing K++ second you are not using i even you cant use i value as i=s.length(); you always need to use till -1 because array starts from 0.

    better option is:

    String result = Arrays.stream(input.split(" ")).filter(p-> p.length()>0).map(p-> p.trim()).collect(Collectors.joining(" "));