Java Program to Replace the Spaces of a String with a Specific Character


In this article, we will understand how to replace the spaces of a string with a specific character. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: Java Program is fun to learn
Input character: $

The desired output would be

The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

Algorithm

Step 1 - START
Step 2 - Declare a string namely input_string, a char namely input_character.
Step 3 - Define the values.
Step 4 - Using the function replace(), replace the white space with the specified character.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java Program is fun to learn";
      System.out.println("The string is defined as: " +input_string);
      char input_character = '$';
      System.out.println("The character is defined as: " +input_character);
      input_string = input_string.replace(' ', input_character);
      System.out.println("The string after replacing spaces with given character is: ");
      System.out.println(input_string);
   }
}

Output

The string is defined as: Java Program is fun to learn
The character is defined as: $
The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Demo {
   static void space_replace(String input_string, char input_character){
      input_string = input_string.replace(' ', input_character);
      System.out.println("The string after replacing spaces with given character is: ");
      System.out.println(input_string);
   }
   public static void main(String[] args) {
      String input_string = "Java Program is fun to learn";
      System.out.println("The string is defined as: " +input_string);
      char input_character = '$';
      System.out.println("The character is defined as: " +input_character);
      space_replace(input_string, input_character);
   }
}

Output

The string is defined as: Java Program is fun to learn
The character is defined as: $
The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

Updated on: 30-Mar-2022

742 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements