简体   繁体   中英

How do I account for spaces while reversing every word in a sentence?

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);



}

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.

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM