Adam
Adam

Reputation: 365

Cycling through a string, and separate by words?

I'm trying to reverse a given string, and I've already fully reversed it, but now I need to reverse each word by itself so that they're readable.

e.g. input: Reverse this string.

current output: .gnirts siht esreveR

desired output: string. this Reverse

Is there some way I can run my string reversing function again on each particular word?

Upvotes: 0

Views: 81

Answers (2)

75inchpianist
75inchpianist

Reputation: 4102

run your reverse alroithm again on each of the results of strtok

    char* token = strtok(str, ' ');

    while (token)
    {
       reversedWord = YourReverseAlgorithm(token);
        token = strtok(0, ' ');
    }

each call to strtok gives you the token of the original string up to the delimitting character, which in your case is ' '. Simple conscise, and works.

Upvotes: 0

perreal
perreal

Reputation: 97948

If you have a reverse function which accepts start and end offsets for the string:

void rstr(char *s, int start, int end) {
  /* ... */
}

int main(){
  char str[] = "this is a sentence of words";
  int i, p;
  rstr(str, 0, strlen(str));
  for (p = i = 0; i <= strlen(str); i++) {
    if (str[i] == ' '  || i == strlen(str)) {
      rstr(str, p, i); 
      p = i + 1;
    }   
  }
  printf("%s\n", str);
  return 0;
}

Upvotes: 1

Related Questions