Java program to replace every space in a string with hyphen

Given a string, the task is to replace all spaces between words with a hyphen "-".

Examples: 

Input: str = "Geeks for Geeks."
Output: Geeks-for-Geeks.

Input: str = "A computer science portal for geeks"
Output: A-computer-science-portal-for-geeks

Approach: 

  1. Traverse the entire string character by character.
  2. If the character is a space, replace it with a hyphen "-".

 

// Java program to replace space with -

class GFG
{
	
	// Function to replace Space with -
	static String replaceSpace(String str)
	{
		
		String s = "";
		
		// Traverse the string character by character.
		for (int i = 0; i < str.length(); ++i) {
	
			// Changing the ith character
			// to '-' if it's a space.
			if (str.charAt(i) == ' ')
				s += '-';
			
			else
				s += str.charAt(i);
			
		}
	
		// return the modified string.
		return s;
	
		
	}
	
	
	public static void main(String []args)
	{
	
		// Get the String
		String str = "A computer science portal for geeks";
		
		System.out.println(replaceSpace(str));
	
	
	}

}

Output: 

A-computer-science-portal-for-geeks

Time Complexity: O(N)

 

Submit Your Programming Assignment Details