L
lovecreatesbea...
I want to write a function to reverse the order of words to make it
read from right to left, but it doesn't work. Can you help me and
point out my mistakes. Thank you for your time.
#include <string.h>
#include <ctype.h>
/* Reverse order of words in a sentence in a string to read it from
right to
* left. * For example:
*
* " hello world !! ! "
*
* becomes
*
* " ! !! world hello "
*
* (heading and tailing blanks should be reserved):
*/
char *rttolt(char str[])
{
enum STATUS{SPC, NSPC, UNDEF};
char *p1 = str, *p2, *p3, ch;
int len = strlen(str);
enum STATUS prestt;
if (!str)
return NULL;
prestt = UNDEF;
for (; len != 0; len--){
if (!isspace(str[len - 1])){
switch ((int)prestt){
case SPC:
for (p3 = &str[len]; isspace(*p3); p3++){
ch = *p3;
for (p2 = &str[len - 1]; p2 >= p1; p2--)
*(p2 + 1) = *p2;
*p2 = ch;
p1++;
}
break;
}
prestt = NSPC;
} else if (isspace(str[len - 1])){
switch ((int)prestt){
case NSPC:
for (p3 = &str[len]; !isspace(*p3); p3++){
ch = *p3;
for (p2 = &str[len - 1]; p2 >= p1; p2--)
*(p2 + 1) = *p2;
*p2 = ch;
p1++;
}
break;
}
prestt = SPC;
}
}
return str;
}
#include <stdio.h>
int main(void)
{
char a[] = "hello world !";
printf("%s, %d\n", a, strlen(a));
rttolt(a);
printf("%s, %d\n", a, strlen(a));
return 0;
}
read from right to left, but it doesn't work. Can you help me and
point out my mistakes. Thank you for your time.
#include <string.h>
#include <ctype.h>
/* Reverse order of words in a sentence in a string to read it from
right to
* left. * For example:
*
* " hello world !! ! "
*
* becomes
*
* " ! !! world hello "
*
* (heading and tailing blanks should be reserved):
*/
char *rttolt(char str[])
{
enum STATUS{SPC, NSPC, UNDEF};
char *p1 = str, *p2, *p3, ch;
int len = strlen(str);
enum STATUS prestt;
if (!str)
return NULL;
prestt = UNDEF;
for (; len != 0; len--){
if (!isspace(str[len - 1])){
switch ((int)prestt){
case SPC:
for (p3 = &str[len]; isspace(*p3); p3++){
ch = *p3;
for (p2 = &str[len - 1]; p2 >= p1; p2--)
*(p2 + 1) = *p2;
*p2 = ch;
p1++;
}
break;
}
prestt = NSPC;
} else if (isspace(str[len - 1])){
switch ((int)prestt){
case NSPC:
for (p3 = &str[len]; !isspace(*p3); p3++){
ch = *p3;
for (p2 = &str[len - 1]; p2 >= p1; p2--)
*(p2 + 1) = *p2;
*p2 = ch;
p1++;
}
break;
}
prestt = SPC;
}
}
return str;
}
#include <stdio.h>
int main(void)
{
char a[] = "hello world !";
printf("%s, %d\n", a, strlen(a));
rttolt(a);
printf("%s, %d\n", a, strlen(a));
return 0;
}