首页 > 解决方案 > 使用 C 程序反转句子中的单个单词(不使用 strrev 等库函数)

问题描述

如标题所述:如果 I/P = "This is a sentence",则 O/P 应为 = "sihT si a ecnetnes" 在我的代码中,它要求输入大小,但输入时它只是跳过字符串输入部分并打印空白输出。有什么帮助吗?

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int size=0, length, i;
    printf("Kindly enter the size of the string that you want to enter : ");
    scanf("%d", &size);
    char* input, * reversed_string, * temp, *temp1, *temp2;

    input = (char*)malloc(size * sizeof(char) + 1);
    reversed_string = (char*)malloc(size * sizeof(char) + 1);
    temp = input;
    
    printf("\nEnter the string :\n");
    gets_s(input, size);

    i = 0;
    temp2=reversed_string;

    while (*input != '\0')
    {
        while (*input == 32)//skip spaces and find the starting of the words
            input++;

        length = 0;
        temp1 = input;
        while (*temp1 != 32 || *temp1 != '\0')//once a starting of the word is found, find its length
        {
            length++;
            temp1 = temp1 + 1;
        }
        temp1 = input;

        short temp_index = length - 1, flag = 0;
        while (temp_index >= 0)//copy the reversed word letter by letter
        {
            flag++;
            *(reversed_string + i) = *(temp1 + temp_index);
            temp_index = temp_index - 1;
            i = i + 1;
        }
        if (flag == 0)//increment the index by 1 if no word added
        {
            input = input + 1;
            i = i + 1;
        }
        else// or increment the index by the number of letters added
        {
            *(reversed_string + i) = 32;
            input = input + temp_index;
        }

    }
    *(reversed_string + i) = '\0';
    reversed_string = temp2;
    printf("\nThe string with reversed words is :\n%s.\n\n", reversed_string);
    system("pause");
    return 0;
}

标签: cstring

解决方案


推荐阅读