Q:

Java Program to replace the spaces of a string with a specific character

belongs to collection: Java String Programs

0

In this program, we need to replace all the spaces present in the string with a specific character.

  1. String: Once in a blue moon
  2. String after replacing space with '-': Once-in-a-blue-moon

One of the approach to accomplish this is by iterating through the string to find spaces. If spaces are present, then assign specific character in that index. Other approach is to use a built-in function replace function to replace space with a specific character.

For programming, follow the algorithm given below:

Algorithm

  • STEP 1: START
  • STEP 2: String string = "Once in a blue moon".
  • STEP 3: char ch = '-'
  • STEP 4: String = string.replace(' ', ch)
  • STEP 5: PRINT "String after replacing spaces with given character:"
  • STEP 6: PRINT string.
  • STEP 7: END

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

public class ReplaceSpace    
{    
    public static void main(String[] args) {    
        String string = "Once in a blue moon";    
        char ch = '-';    
            
        //Replace space with specific character ch    
        string = string.replace(' ', ch);    
            
        System.out.println("String after replacing spaces with given character: ");    
        System.out.println(string);    
    }    
}    

  

Output:

String after replacing spaces with given character: 
Once-in-a-blue-moon

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java Program to determine whether a given string i... >>
<< Java Program to replace lower-case characters with...