我试图在一个句子中反转单词的字母。我也试图将这些单词存储在一个新的char数组中。目前我收到运行时错误,对于我所有的调整我无法解决。我的方法是创建一个与句子长度相同的新char数组。然后遍历句子直到我达到''字符。然后向后循环并将这些字符添加到单词中。然后将单词添加到新句子中。任何帮助将不胜感激。
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;
}
答案 0 :(得分:3)
#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;
}
答案 1 :(得分:2)
逻辑上,这里:
j = sentence[i]
start =sentence[i +1];
start
和j
是char数组中的索引位置,您试图为它们分配char
,这会搞砸所有内容。
应该是:
j= i;
start = i +1;
如果你的算法是正确的。
答案 2 :(得分:1)
另一种变体......
int main(int argc, const char *argv[])
{
char sentence [] = "this is a sentence";
size_t len = strlen(sentence);
char *newSentence = malloc(len + 1);
char *ptr_src = sentence;
char *ptr_dst = newSentence;
while(ptr_src)
{
char *next, *t;
next = strchr(ptr_src, ' '); // find next space
if (!next) next = sentence + len; // if not found, next = EOL
for (t = next; t > ptr_src;)
{
*ptr_dst++ = *--t;
}
if (*next)
{
*ptr_dst++ = *next++;
ptr_src = next;
}
else
{
*ptr_dst = 0;
break;
}
}
printf("[%s]",newSentence);
return 0;
}
答案 3 :(得分:1)
你的程序有很少的bug。我试图在此计划中删除:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char sentence [] = "this is a sentence";
char *newSentence = (char *)malloc(strlen(sentence)+1);
int i,j,start, k;
start = 0;
for(i = 0;; i++)
{
if(sentence[i] == ' ' || sentence[i] == '\0') //sentence[i] == '\0' for the last word.
{
char *word = (char *) malloc((i - start)+1);
for(j = i-1, k = 0; j >= start; j--, k++)
{
word[k] = sentence[j];
}
word[k++] = ' '; //space after each word
word[k] = '\0';
strcat(newSentence,word);
start = i+1;
}
if (sentence[i] == '\0')
break;
}
printf("%s\n",newSentence);
return 0;
}
答案 4 :(得分:0)
strcat(newSentence,word);
newSentence
必须是一个字符串。字符串是由第一个空字符终止并包含第一个空字符的连续字符序列
编辑:对于上面所写的内容,此答案已被4次下调。如果您认为不正确,请解释。否则请删除你的downvote。