如何在反转句子中的每个单词时考虑空格? [英] How do I account for spaces while reversing every word in a sentence?

查看:56
本文介绍了如何在反转句子中的每个单词时考虑空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,该程序应从用户那里获取输入,并反转句子中的每个单词。因此,如果我曾经使用过 Hello World,则应打印 olleH dlroW,但到目前为止,它的打印内容是 dlroW olleH。因此,我的程序会反转整个句子,而不仅仅是特定的单词。不太确定该如何处理。我尽了全力。

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



}


推荐答案

像这样修复

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

这篇关于如何在反转句子中的每个单词时考虑空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆