Thursday, January 20, 2011

BlueJ Program On How To Remove Extra Blank Spaces From A String



Today I will discuss about a string modification program. String class has a function ‘String trim ()’ which removes leading and trailing spaces from a string value. But what happens if there are more than one blank space between two words in a text? The above ‘trim ()’ function can not remove such blank spaces from a string.

How to proceed on this string modification program

Firstly the leading and trailing space from the string is to be removed, if any. Function ‘String trim ()’ will perform this job. Next action is to access every character and check if there is consecutive blank spaces in the string. The characters and only one blank space following any character is to be concatenated in another string object. If there are multiple blank spaces, they should not be concatenated in the second string object which will hold the modified string.

Codes of removing extra blank spaces from a string object

import java.io.*;
class Words
{
 int w;
 BufferedReader br;
 String text,modified="";
  public static void main(String args[])throws IOException
   {
  Words ob=new Words();
 ob.accept();
 ob.result();
  }
  Words()
  {
   br=new BufferedReader(new InputStreamReader(System.in));
   text="";
   w=0;
  }
public void accept()throws IOException
{
 System.out.println("Enter the Sentence:");
 text=br.readLine().trim();
}
public void result()
{
int i,len;
char ch;
 System.out.println("The entered sentence ="+text);
 len=text.length();
 for(i=0;i< len;i++)
 {
 ch=text.charAt(i);
 if(ch==' ' && w==1)
 {
 w=0;
 modified=modified+ch;
 }
 else if(ch!=' ')
 {
 modified=modified+ch;
 w=1;
 }
 }
 System.out.println("The modified sentence ="+modified);
}
}
Technical analysis of the above string modification program

The job of removing extra blank spaces from the string is done within the ‘public void result ()’ function. Using a for loop each character of the string is accessed. An int type variable ‘w’ is used to notify if consecutive blank spaces are there in the string. Initial value of ‘w’ is set to ‘0’. Whenever any alphaber is found in the string, the value of the variable ‘w’ is set to ‘1’. On the process of checking each characters, if any blank space is found and the value of ‘w’ is ‘1’ at that time, the blank space is concatenated in the second string object. At the same time the value of ‘w’ is reset to ‘0’ so that consecutive two blank spaces are not taken in the modified string object.

2 comments:

  1. we can use string tokenizer
    to extract words and then and print a space before printing each word.

    ReplyDelete
    Replies
    1. It's possible but I think in ICSE, students are not permitted to use the StringTokenizer class.

      Delete

Subscribe via email

Enter your email address:

Delivered by FeedBurner