Replacing space with a hyphen in C++

C++Server Side ProgrammingProgramming

In this C++ program, the space in the string will be replaced with the hyphen. Firstly, the length of the string is determined by the length() function of the cstring class, then hyphen is filled into the space of the sentence by traversing the string as follows.


 Live Demo

#include <cstring>
#include <iostream>
using namespace std;
int main(){
   // raw string declaration
   string str = "Coding in C++ programming";
   cout<<"Normal String::"<<str<<endl;
   for (int i = 0; i < str.length(); ++i) {
      // replacing character to '-' with a 'space'.
      if (str[i] == ' ') {
         str[i] = '-';
   // output string with '-'.
   cout <<"Output string::"<< str << endl;
   return 0;


The output of the program is yield with hyphen tweak as following when the user enters the string as following;

Normal String::Coding in C++ programming
Output string::Coding-in-C++-programming
Published on 29-Nov-2019 15:25:18