gpt4 book ai didi

c - C语言中的逆序词

转载 作者:行者123 更新时间:2023-11-30 18:20:39 24 4
gpt4 key购买 nike

我正在尝试颠倒句子中单词的字母。我还尝试将这些单词存储在一个新的字符数组中。目前,我遇到了运行时错误,尽管我进行了所有调整,但仍无法解决该错误。我的方法是创建一个与句子长度相同的新字符数组。然后循环遍历该句子,直到到达“”字符。然后向后循环并将这些字符添加到单词中。然后将单词添加到新句子中。任何帮助将不胜感激。

int main(void) {
char sentence [] = "this is a sentence";
char *newSentence = malloc(strlen(sentence)+1);
int i,j,start;
start = 0;

for(i = 0; i <= strlen(sentence); i++)
{

if(sentence[i] == ' ')
{
char *word = malloc((i - start)+1);
for(j = sentence[i]; j >= start; j--)
{
word[j] = sentence[j];
}
strcat(newSentence,word);
start =sentence[i +1];
}
}
printf("%s",newSentence);
return 0;
}

最佳答案

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

int main(void) {
char sentence [] = "this is a sentence";
char *newSentence;
int i,j,start, len;
start = 0;
len = strlen(sentence);
newSentence = malloc(len+1);
*newSentence = '\0';

for(i = 0; i <= len; i++)
{
if(sentence[i] == ' ' || sentence[i] == '\0')
{
char *word = malloc((i - start)+1);
int c = 0;
for(j = i - 1; j >= start; j--)
{
word[c++] = sentence[j];
}
word[c]='\0';
strcat(newSentence,word);
if(sentence[i] == ' ')
strcat(newSentence," ");
start = i + 1;
free(word);
}
}
printf("%s",newSentence);
return 0;
}

关于c - C语言中的逆序词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16022220/

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