gpt4 book ai didi

c - 反转C中的二维字符数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:45 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来反转整个字符串,并且还可以多次打印反转字符串的每个单词。例如我的字符串是:“2狐狸跳过懒狗。”为此,输出应该是:.god .god yzal yzal eht eht revo revo spmuj spmuj xoF xoF。我试图将每个单词存储在一个二维数组中,然后反转每个单词,但我无法做到这一点。这是我的代码。请帮忙注意:我们如何在控制台中提供EOF

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

int main() {
char string[100][100];
char ch;
int i = 0, j = 0, l = 0, count = 0, x = 0, y = 0;
while ((ch = getchar()) != EOF) {
string[i][l++] = ch;
if (ch == ' ') {
string[i][l] = '\n';
i++;
l = 0;
count++;
}
}
for (x = 0; x <= count; x++) {
int length = strlen(string[x]) - 1;
for (y = length; y >= 0; --y)
printf("%s", string[y]);
}
return 0;
}

最佳答案

这里是对您的代码的一些更改,请查看注释以获取解释。

int main()
{
char string[100][100];
char ch;
int i=0,j=0, l=0, count=0, x=0, y=0;
while((ch=getchar())!=EOF)
{
string[i][l++] = ch;
if(ch==' ')
{
string[i][l] = '\0'; //make the string null terminated otherwise you cant work with its length
i++;
l=0;
count++;
}
}
string[i][l]='\0'; //make the last string null terminated
for(x=count; x>=0; x--) //read from last counter
{
int length = strlen(string[x])-1;
for(y=length; y>=0; --y)
{
printf("%c", string[x][y]); //print by each character and not string.
}
}
return 0;

关于c - 反转C中的二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097973/

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