-1

I am trying to flip each word in a sentence in C so that something like:

"I like big dogs" would become: "dogs big like I"

I have the following code so far:

//  the following effectively flips a sentence so "I like big dogs" would become
    "sgod gib ekil I"

for (i=0;i<length/2;i++){ // length is length of the string
    temp=ret[length-(i+1)]; //ret is the string
    ret[length-(i+1)]=ret[i];
    ret[i]=temp;
}
    //now this part should flip each individual word to the right way
//pos and lengthPlacer are both initialized as 0
while(pos<length){
    lengthPlacer++;
    if (ret[lengthPlacer]==' ' || lengthPlacer==length){
for (i=pos;i<(lengthPlacer)/2;i++){
    temp=ret[lengthPlacer-(i+pos+1)];
    ret[lengthPlacer-(i+pos+1)]=ret[i];
    ret[i]=temp;
}   
    pos=lengthPlacer+1;
    }
}
return ret; //this returns "dogs gib ekil I" unfortunately (only flips 1st word)

}

Any help is much appreciated. Thanks!

user2019594
  • 353
  • 1
  • 3
  • 9

1 Answers1

0

You are incrementing the pos variable at the same time as the lengthPlacer variable. You need an inner loop to increment first until the space and then the loop to reverse is after that.

while(pos<length){
  while (lengthPlacer < length)
    if (ret[lengthPlacer]==' ') break;
  }
  next = pos + (lengthPlacer-pos)/2;
  while (pos < next){
    etc...
  }   
  // Also here skip any spaces that might be dangling
}