I wrote a program that reverses each word in a string. For example hello and goodbye is turned into olleh dna eybdoog. My program works, however the time efficiency is o(n^2) and I probably could of written less code. I am trying not to use any of the string.functions() ( I used string.length() once). Any tips or suggestions would be appreciated.
#include <iostream>
using namespace std;
void breakString(string& me, char * otherOne, int len, int count);
void reverseString(char* s);
int main () {
string me=("hello and goodbye");
char * otherOne;
int len=0;
int count=0;
for (len; len<me.length()+1; len++){
count++;
if (me[len]=='\0') {
otherOne=new char[count];
len-=count-1;
count=0;
for (len; me[len]; len++){
otherOne[count]=me[len];
count++;
}
reverseString(otherOne);
breakString( me, otherOne, len, count);
}
if (me[len]==' ' ) {
otherOne=new char[count];
len-=count-1;
count=0;
for (len; me[len] != ' '; len++){
otherOne[count]=me[len];
count++;
}
reverseString(otherOne);
breakString( me, otherOne, len, count);
count=0;
otherOne=NULL;
delete[]otherOne;
}
}
delete[]otherOne;
cout << me;
return 0;
}
void reverseString(char* s)
{
int len =0;
char swap;
for (len=0; s[len] != '\0'; len++);
for ( int i=0; i<len/2; i++)
{
swap = *(s+i);
*(s+i)= *(s+len-i-1);
*(s+len-i-1) = swap;
}
}
void breakString(string &me, char * otherOne, int len, int count){
len-=count;
for (count=0; otherOne[count]; count++){
me[len]=otherOne[count];
len++;
}
}
Isn’t far simple something like
?
Complexity is O(n): each word is read twice (or, better, one and a half times): once since the program finds a space or a \0, then, in the nested for, the word is reversed.
indexindicates the word starting char.