Computer Science

While typing, a typist has created two or more consecutive blank spaces between the words of a sentence. Write a program in Java to eliminate multiple blanks between the words by a single blank.

Sample Input:
Indian   Cricket   team   tour   to   Australia

Sample Output:
Indian Cricket team tour to Australia

Java

Java String Handling

18 Likes

Answer

import java.util.*;

public class KboatMultipleBlanks
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = in.nextLine();
        int len = str.length();
        
        StringTokenizer st = new StringTokenizer(str);
        String newStr = ""; //Empty String
        
        while (st.hasMoreTokens()) {
            String word = st.nextToken();
            newStr += word + " ";
        }
        
        newStr = newStr.trim();
        
        System.out.println("Output String:");
        System.out.println(newStr);
    }
}

Output

Answered By

5 Likes


Related Questions