Java Code to Remove Spaces from String - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Monday, September 25, 2017

Java Code to Remove Spaces from String

Write a Java Code to Remove Spaces from String

Program:
/* Java Program Example - Remove Spaces from Sentence */

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{
String str, strWithoutSpace;
int i;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a Sentence : ");
str = scan.nextLine();

//1. Using replaceAll() Method

strWithoutSpace = str.replaceAll(" ", "");

System.out.println(strWithoutSpace);

//2. Without Using replaceAll() Method

char[] strArray = str.toCharArray();

StringBuffer sb = new StringBuffer();

for (i = 0; i < strArray.length; i++)
{
if( (strArray[i] != ' ') && (strArray[i] != '\t') )
{
sb.append(strArray[i]);
}
}

System.out.println(sb);
}
}

Output:
Enter the sentence:This is a Java Program
ThisisaJavaProgram

No comments:

Post a Comment