c - 使用 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;
}
解决方案
推荐阅读
- html - 创建下标的下标
- java - 为什么Java类文件版本从45开始?
- javascript - 如何检查数据是否已完成加载以使用异步管道 Angular 8
- javascript - 自第二次请求以来,AJAX 成功无法正确呈现
- ms-access - 如何正确创建 SQL 查询
- c++ - 这是词法分析器的代码,谁能详细解释一下这段代码?
- python - 如何修复 TypeError: +: 'int' 和 'str' 不支持的操作数类型
- .net - 可以使用不是长期运行的任务的长期任务吗?
- c# - 使用协程设置进行 PlayMode 测试
- python - 根据另一个数据框中的行条件,在一个数据框中查找值