Tuesday, 10 December 2013

JAVA: Removing White Spaces from the String without using inbuilt String functions Like ReplaceAll(), Trim(), Split().



Below is the code.
package Strings;

public class removingwhitespaceWithoutFunctions {
    public static void main(String args[]){
        String x = "  aslam anweranwer      hello hi we hello a  ";
        int y = x.length();
        char c[]= x.toCharArray();
        char h[] ;
        int j=0,t=0;
        for(int i=0;i<y;i++){
            int m = c[i];
        if(m ==32){       // we can compare space also, here i am comparing the asccii code.
            ++t;                // count how many spaces are there.
}
        }
        h = new char[y - t]; // set the length of the array which is going to hold the new string.
        System.out.println(h.length);
        for(int i=0;i<y;i++){
            int m = c[i];
        if(m !=32){
   
        h[j]=c[i];   
        j=j+1;   
        }
        }
       
    System.out.println(h);
        }}

No comments:

Post a Comment