String

I am writing a program now and I am typing in a lot of words through a loop and i need spaces in between each letter when they are printed out. When i type in the word i put it under word as such.. cout<<word; how can i make spaces in this word so the word printed can have s p a c e s in between each letter.
well, you could [print a char, print a space, repeat]
1
2
for(int i = 0; mystring[i] != 0; i++)
   std::cout << mystring << ' ';

or if you want to save it into another string,
1
2
3
4
5
6
//create a string 2 times longer than mystring called newstring
//you could initialize it to 0 (if you use char array)
for(int i = 0; mystring[i] != 0; i+=2){
   newstring[i] = mystring[i/2];
   newstring[i+1] = ' ';
}

you can further improve these codes, so that there is no space after the last letter.
I'm sorry hamsterman but I really don't like that second idea. Strings, like all arrays, don't like to be resized. I even tried to get your code there to work with a few adjustments and it's a no go.

I guess if you knew ahead of time what the size of the input would be it could be hard coded but that's not a great suggestion.

Also for the OP, hamsterman has a typo in his first suggestion. The first idea should read:

1
2
3
4
for (int i = 0; i <= mystring.length(); i++) //Or for (int i = 0; i <= mystring.sizeof(); i++) if 'mystring' is a char array
{
   std::cout << mystring[i] << ' ';
}
Last edited on
Just fixing a few things:

1
2
3
4
5
6
7
for (int i = 0; i < mystring.length(); i++)
{
    if(i == mystring.length() - 1)
        std::cout << mystring[i];
    else
        std::cout << mystring[i] << ' ';
}

//Or for (char* p = mystring; *p != 0; ++p) if 'mystring' is a char array

remembering to use *p instead of mystring[i] in that last case.
Not that it's very important, but this code would be slightly more efficient than filipe's post.

1
2
3
std::cout << mystring[0];
for (int i = 1; i < mystring.length(); i++)
    std::cout << ' ' << mystring[i] ;
It would indeed be nice to know if OP was talking about c string or std::string..

@Computergeek01, what's wrong with it?
If they are char*, either newstring = new char[strlen(mystring)+1];, or of you don't like dynamic memory, char newstring[160]; //where mystring is char[80]
If they are std::strings, string newstring(mystring.length, ' '); //and you don't need line 5 any more

@filipe, how is *p better than mystring[i]?
@filipe, how is *p better than mystring[i]?


1
2
3
4
for(char* p = mystring; *p != 0; ++p)
{
    std::cout << mystring[i]; // what is i?
}
oh, now I understand.. sorry, I somehow assumed you were saying that for(char* p = mystring; *p != 0; ++p) is better than for(int i = 0; mystring[i] != 0; i++)
Topic archived. No new replies allowed.