Replacing space with hyphen in a string

This program is to replace all the spaces with hyphens in a string.
I don't understand why we used int x1=strlen(string); here ??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
int main ()
{ clrscr();
char string[80];
cout<<"Enter string \n";
cin.getline(string,80);
int x1=strlen(string);
for(int i=0;string[i]!='\0';i++)
if(string[i]==' ')
string[i]='_';
cout<<"The changed string is \n";
cout.write(string,x1);
return 0; }



x1 is used for the cout.write() to write only the number of characters in the original string. This is done because string is a character array with a size between 1 and 80. the strlen function figures out how big it really is and then only that many elements are written in the cout. There are a lot of C references here. If you want to make it c++, use the std::string type instead of making a character array.

I would just do the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream.h>
using namespace std;

int main ()
{ 
  std::string TheString
  cout<<"Enter string \n";
  cin.getline(TheString);

  for(int i=0;i <TheString.size();i++)
    if(TheString[i]==' ')
        TheString[i]='_';

  cout<<"The changed string is \n" << TheString;
return 0; 
}
Last edited on
Thank you so much...ur code is much simpler..I myself made a similar to ur code few minutes ago ! :)
Topic archived. No new replies allowed.