Replace Each Space with a Character in a String in Java
Replacing spaces in a string is a common string manipulation task. It is often used in formatting text, URL encoding, and input normalization.
In this program, we replace every space character (' ')
with a given character without using built-in string replacement methods.
How the Logic Works
- Convert the string into a character array.
- Traverse each character.
- If a space is found, replace it with the given character.
- Reconstruct the string.
Example 1
Input: "Java Programming"
Replace with: '-'
Output: Java-Programming
Example 2
Input: "Hello World Java"
Replace with: '*'
Output: Hello*World*Java
Java Program to Replace Each Space with a Character
import java.util.Scanner;
public class ReplaceSpace {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
System.out.print("Enter replacement character: ");
char replaceChar = sc.next().charAt(0);
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ' ') {
chars[i] = replaceChar;
}
}
System.out.println("Modified String: " + new String(chars));
}
}
Sample Output
Enter a string: Practice makes perfect
Enter replacement character: _
Modified String: Practice_makes_perfect
Important Notes
- No
replace()orreplaceAll()method is used. - Only space characters are replaced.
- Time complexity is O(n).
Practice Challenges
- Replace spaces with multiple characters like "%20".
- Replace only the first occurrence of space.
- Count how many spaces were replaced.
This problem helps in understanding character-level manipulation and safe string transformations in Java.