Skip to content
Related Articles

Related Articles

Improve Article

Program to replace every space in a string with hyphen

  • Difficulty Level : Basic
  • Last Updated : 28 May, 2021

Given a string, the task is to replace all the spaces between the words with a hyphen character ‘-‘.
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 whole string character by character.
  2. If the character is a space, replace it with hyphen ‘-‘.

Below is the implementation of the above approach: 

C++




// C++ program to replace space with -
 
#include <cstring>
#include <iostream>
using namespace std;
 
int main()
{
 
    // Get the String
    string str = "A computer science portal for geeks";
 
    // 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[i] == ' ') {
 
            str[i] = '-';
        }
    }
 
    // Print the modified string.
    cout << str << endl;
 
    return 0;
}

Java




// 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));
     
     
    }
 
}

Python3




# Python 3 program to replace space with -
 
# Driver Code
if __name__ == '__main__':
     
    # Get the String
    str = "A computer science portal for geeks"
     
    # Traverse the string character by character.
    for i in range(0, len(str), 1):
         
        # Changing the ith character
        # to '-' if it's a space.
        if (str[i] == ' '):
            str = str.replace(str[i], '-')
             
    # Print the modified string.
    print(str)
     
# This code is contributed by
# Surendra_Gangwar

C#




     
// C# program to replace space with -
using System;
public 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[i] == ' ')
                s += '-';
              
            else
                s += str[i];
              
        }
      
        // return the modified string.
        return s;
      
          
    }
      
      
    public static void Main()
    {
      
        // Get the String
        String str = "A computer science portal for geeks";
          
        Console.Write(replaceSpace(str));
      
      
    }
  
}
// This code is contributed by 29AjayKumar

PHP




<?php
// PHP program to replace space with -
 
// Get the String
$str = "A computer science portal for geeks";
 
// Traverse the string character by character.
for ($i = 0; $i < strlen($str); ++$i)
{
 
    // Changing the ith character
    // to '-' if it's a space.
    if ($str[$i] == ' ')
    {
        $str[$i] = '-';
    }
}
 
// Print the modified string.
echo $str . "\n";
 
// This code is contributed
// by Akanksha Rai

Javascript




<script>
      // JavaScript program to replace space with -
 
      // Get the String
      var str = "A computer science portal for geeks";
 
      var newStr = str.split("");
 
      // Traverse the string character by character.
      for (var i = 0; i < newStr.length; ++i) {
        // Changing the ith character
        // to '-' if it's a space.
        if (newStr[i] === " ") {
          newStr[i] = "-";
        }
      }
 
      // Print the modified string.
      document.write(newStr.join("") + "<br>");
    </script>
Output: 
A-computer-science-portal-for-geeks

 

Time Complexity: O(N)

Method #2: Using join() in Python:

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • Join the list using ‘-‘ and store in a string
  • Print the string

Below is the implementation of the above approach:

Python3




# Python program for the above approach
 
def printHyphen(string):
 
    # Split by space and converting
    # String to list and
    lis = list(string.split(" "))
 
    # joining the list and storing in string
    string = '-'.join(lis)
    # returning thee string
    return string
 
 
# Driver code
string = "Text contains malayalam and level words"
print(printHyphen(string))
 
# This code is contributed by vikkycirus

Javascript




<script>
 
// JavaScript program for the above approach
 
function printHyphen(string){
 
    // Split by space and converting
    // String to list and
 
    var lis = string.split(" ")
 
    // joining the list and storing in string
 
    string =  lis.join("-");
 
    // returning the string
    return string;
    }
 
 
// Driver code
var string = "Text contains malayalam and level words";
document.write(printHyphen(string));
 
 
 
 
</script>

Output:

Text-contains-malayalam-and-level-words
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :