C 无法按相反顺序打印单词
我必须用指针按相反的顺序打印一些单词 例如,给定“Hello World”,输出应为“World Hello” 这是我到目前为止所做的,但它没有打印任何内容:C 无法按相反顺序打印单词,c,pointers,C,Pointers,我必须用指针按相反的顺序打印一些单词 例如,给定“Hello World”,输出应为“World Hello” 这是我到目前为止所做的,但它没有打印任何内容: void swap(char *ar){ int tmp1[10], tmp2[10], j = 0, k = 0, a, b, z,i; // must use pointers for (i=0; i<MAX; i++) { if(ar[i] == ' ') //if there's
void swap(char *ar){
int tmp1[10], tmp2[10], j = 0, k = 0, a, b, z,i; // must use pointers
for (i=0; i<MAX; i++)
{
if(ar[i] == ' ') //if there's a space, store the characters before the space to another array and after the space to another
{
for(j = 0; j<i; j++) // tmp1
tmp1[j] = ar[j];
for( j = 0; j<MAX-i; j++) //MAX - i would be range of j
for(k = i+1; k<MAX; k++) //tmp2
tmp2[j] = ar[k];
}
}
i = 0;
while(1)
{
while(tmp2[i] != '\0' && i<sizeof(tmp2)) // finding the size of tmp2
a++;
}
for(j=0; j<a; j++) // overwriting the original array
ar[j] = tmp2[j];
j++; // incrementing j so that there would be a space between the new array
z = j;
i=0;
while(1) //finding the size of tmp1
{
while(tmp1[i] != '\0' && i<sizeof(tmp1))
b++;
}
//idk pls help
for( z=0 ; z<MAX; z++) //overwriting the original array
for(k = 0; k<b; k++)
ar[z] = tmp1[k];
//idk pls help
for (i = 0; i < MAX; i++) // outputting the required result
printf("%c", *(ar+i));
printf("\n");
}//eg if input is Hello World the output should be World Hello//idk pls help
无效交换(char*ar){
int tmp1[10],tmp2[10],j=0,k=0,a,b,z,i;//必须使用指针
对于(i=0;i我认为您的问题是而(1)
循环
无限循环
我希望这能有所帮助。为什么不使用strtok拆分字符串并在第一个单词之前打印第二个单词?您现在所做的是非常低效的,6个循环和10个系统调用,您可以执行1个循环和1个系统调用!如果您需要,我可以为您编写代码,请告诉我
void swap(char *ar){
int i, z;
for(z = 0; ar[z]; z++) //find the index of the space
{
if (ar[z] = ' ')
break;
}
for(i = z + 1; ar[i]; i++)
printf("%c",ar[i]); //print from space to end of string
printf(" ");
for(i = 0; i < z; i++)
printf("%c",ar[i]); //print from start of string to space
printf("\n");
}
无效交换(char*ar){
int i,z;
for(z=0;ar[z];z++)//查找空间的索引
{
如果(ar[z]='')
打破
}
对于(i=z+1;ar[i];i++)
printf(“%c”,ar[i]);//从空格打印到字符串末尾
printf(“”);
对于(i=0;i
你面临的问题是什么?我猜你的问题是而(1)
循环…“无限循环”。它没有打印任何内容。请编辑问题并缩进您的代码。在给出注释/答案后,不要更改代码,因为这会使它们无法理解。添加更新。我回滚了您上次的更改。嗯,那么我应该怎么做呢?我告诉您可能有什么问题……随着您的学习,您必须进一步研究然后自己尝试另一种解决方案。如果我说怎么做,你将学不好。你也需要存储在另一个数组中吗?为什么不立即打印?也不要使用MAX作为循环条件,使用ar[I]!=Null代替停止循环我们不需要将它存储在另一个数组中…嗯,你能帮我写吗?请尝试一下这段代码应该可以工作!不是最有效的,但肯定更严格!行“if(ar[z]=””应该是“if(ar[z]=”)