gpt4 book ai didi

更改字符串中某些单词的顺序

转载 作者:行者123 更新时间:2023-11-30 15:01:17 27 4
gpt4 key购买 nike

我已经尝试解决这个练习一周了,但我的代码不起作用,我不明白为什么以及如何更改它。练习是:从用户处接收一个长度,然后从用户处接收一个与“length”一样长的字符串(str),然后从用户处接收一个数字(int n)。然后我需要执行函数 'void ReverseNumWords (char*str, int n) ).该函数反转字符串中的前n个单词。例如:对于“我是你的父亲星球大战”且 n=3:“你是我的星球大战之父”。假设这些单词是用 ' ' 分隔的,这是正确的。谢谢您的帮助!!

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

void Reverse()
{

int len,num;
char *str;
printf("Please enter how many chars to allocate:\n");
//Asking from the user the length of a string.
scanf("%d", &len);
//Allocating memory for the string.
str = (char*)calloc(len, sizeof(int));
//Making sure the allocation was successful.
if (!str)
printf("Error: Cannot allocate Memory\n");
printf("Allocated %d chars\n", len);
printf("Please enter your string:\n");
scanf("%s", str);
printf("Please enter how many words to reverse:\n");
scanf("%d", &num);
ReverseNumWords(*str, num, len);
free(str);
}

void ReverseNumWords(char*str, int num,int len)
{

char *sub;
char temp;
//Allocating memory for the string.
sub = (char*)calloc(len, sizeof(int));
//Making sure the allocation was successful.
if (!sub)
printf("Error: Cannot allocate Memory\n");
int i, j,l;
i = j = 0;
for (; i < len, j <= num; i++)
if (str[i] == '\0' || str[i] == 0)
j++;

for (l = 0; l < i; l++)
sub[i] = str[i];

for (j = 0; j < i; j++)
temp = sub[j];
sub[j] = sub[i - (1+j)];
sub[i - (1+j)] = sub[j];

reverseWords(*sub);


}

void reverseWords(char *sub)
{

char *word_begin = sub;
char *temp = sub;

while (*temp)
{
temp++;
if (*temp == '\0')
{
reverse(word_begin, temp - 1);
}
else if (*temp == ' ')
{
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}

reverse(sub, temp - 1);
}

void reverse(char *begin, char*sub, char *end)
{

char temp;
while (begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
printf("%s\n", sub);
}

最佳答案

你的读取函数应该是这样的

int len,num;
char *str;
printf("Please enter how many chars to allocate:\n");
//Asking from the user the length of a string.
scanf(" %d", &len);
//Allocating memory for the string.
str = (char*)malloc(sizeof(char)*(len+1));
//Making sure the allocation was successful.
if (!str)
printf("Error: Cannot allocate Memory\n");

printf("Allocated %d chars\n", len);
printf("Please enter your string:\n");
scanf(" %[^\n]s", str);

printf("Please enter how many words to reverse:\n");
scanf(" %d", &num);
ReverseNumWords(*str, num, len);
free(str);

因为使用 %s 读取时,您将停在找到的第一个“”(空格)处。并且您想要阅读直到找到\n(输入)。

关于更改字符串中某些单词的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534415/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com