Replace Blank Spaces of String with a Character in Java

java program to replace blank space with given character

In this tutorial we will learn writing java program to replace blank spaces of a String with a given character. The program will accepts one string and one character from the user.

  1. The main string where the space are needed to replaced.
  2. The character which replaces the space in 1st string.
  3. And then returns the final string where the space of main string is replaced by character inserted by user.

For Example

For example

Case 1:  If user is given the string value as ‘ques ol’,

                 and the character value inserted by user is ‘c’

                 then the output generated must be “quescol”.

Case 2:  If user is given the string value as ‘java sfun’,

                 and the character value inserted by user is ‘i’

                 then the output generated must be “javaisfun”.

Program 1 : Replace Space with Given Input using replace() method Java

Output

replace blank spaces of string with character java

Explanation :

Here, the user input string ‘quescol Website’, and a character ‘p’ which replaces all the spaces in string. In order to search all the spaces on sting and replaces it with character, replace function helps to perform this operation. And returns the copy of string ‘quescol Website’ where all spaces if replaced with ‘p’ as we can see in the output generated.

Program 2: Replace Space with Given Input without using replace() method Java

Output

replace blank spaces of string java

Explanation

Here, the user input string ‘quescol best website’, and a character ‘Y’ which replaces all the spaces in string. In order to search all the spaces on sting and replaces it with character as we can see in the output generated.