Reputation: 365
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
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
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