How do I account for spaces while reversing every

2019-08-01 20:55发布

Basically this program should take input from the user and reverse each word in the sentence. So if I ever "Hello World" is should print "olleH dlroW", but as of now it prints "dlroW olleH". So my program reverses the whole sentence and not just the specific words. Not really sure how to approach it. I gave it my best.

#include <stdio.h>
#include <string.h>

void reverse(char *str, int start, int end)
{

    char temp;
    while (start < end)
    {
        if(isspace(str[start]))
        {
            printf("%s ", str);
            start++; 
        }
        else
        {
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }   
    }       
    return;
}

int main()
{
    char word[256];
    int i=0, bound;
    printf("Enter a string\n");
    fgets(word, 256, stdin);
    printf("%s", word);

    bound = strlen(word);
    reverse(word, i, bound-1);
    printf("%s\n", word);



}

标签: c char
3条回答
三岁会撩人
2楼-- · 2019-08-01 21:12

fix like this

#include <stdio.h>
#include <string.h>

void reverse(char *str, int start, int end){
    char temp;
    while (start < end){
        temp = str[start];
        str[start++] = str[end];
        str[end--] = temp;
    }      
}

int main(void){
    char word[256];

    printf("Enter a string\n");
    fgets(word, 256, stdin);
    printf("%s", word);

    size_t pos = 0, start, end;
    do {
        start = (pos += strspn(word + pos, " \t"));
        end = start + strcspn(word + pos, " \t\n");
        reverse(word, start, end-1);
        pos = end;
    }while(start != end);

    printf("%s\n", word);
}
查看更多
beautiful°
3楼-- · 2019-08-01 21:14

Track the point where you start and when you find a space - both integers. If you find a space get a substring from 'start'(first letter) to 'end'(space). Reverse the substring and put it back to original string and go on.

查看更多
做自己的国王
4楼-- · 2019-08-01 21:36

Just change your reverse method to this. I hope this helps.

void reverse_word(char *word, int len){
    int i;
    int j = strcspn(word," ");
    int k = j;
    int check = k/2; // for keeping track of the middle char

    for (i = 0;  i< len ; ++i) {

        if(i == check) {
            j = strcspn((word+k)+1," ");  // get the next space if there is any
            i = k+1;
            j = j+k+1;
            k = j;
            check = i + ((j-i)/2);

        }

        --j;
        char c = word[i];
        word[i] = word[j];
        word[j] = c;
    }

}

results from test

"Hello World working" reverse to --->> olleH dlroW gnikrow

查看更多
登录 后发表回答