gpt4 book ai didi

c - 从右到左在 C 中的数组中滚动一个单词?

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

假设您有(可以是任意长度的字符串)。

char word[] = "Coding is really fun";

还有一些限制为 10 个字符的空“缓冲区”数组。

char buffer[12] = "            "; //initialized with 10 spaces, leaving room for null character.

例如,在第一次通过后 buffer 将是“C”; (C前9个空格)

然后下一个“Co”; (前面8个空格)

下面的代码在一定程度上有效,但是当它达到更大的 i 值时,它开始添加多个字符,然后一遍又一遍地重复添加第一个字符。

int i = 0;
int j;
int k = 0;
char word[] = "Coding is really fun";
char buffer[12] = " ";
buffer[11]='\0';
buffer[10] = word[0];

while(1){
k = 0;
for (j = 10 - i; j < 11; j++){
buffer[j] = word[k];
k++;
}
i++;
}

最后我想滚动 word 直到它一直通过 buffer 然后缓冲区再次为空。

我知道我的问题,这是我的 for 循环。当我超过缓冲区的大小时(i 是我用来跟踪我接下来需要添加到缓冲区的字符的变量),我超过了 10。然后我开始遇到问题。我怎样才能重写它,使 word 基本上从右到左“滑动”通过 buffer

这正是我想要做的,尝试进一步解释它。假设我们有

char word[] = "Hello"; 
char buffer[4] = " " //space for 3 characters.

After the first pass through the loop, buffer should be " H"
After the second pass through the loop, buffer should be " He"
After the third pass through the loop, buffer should be "Hel"
After the fourth pass through the loop, buffer should be "ell"
After the fifth pass through the loop, buffer should be "llo"
After the sixth pass, buffer should be "lo "
After the seventh, buffer should be "o "
After the eighth, buffer should be " " (empty once again).

最佳答案

假设您有一个循环源文本,其中包含您的 word,后跟与缓冲区一样多的空格。这个假想的圆形源文本的大小是

size_t wordsize = strlen(word);
size_t buffsize = strlen(buffer);
size_t icstsize = wordsize + buffsize;

每次移动缓冲区时,都会更改其中的每个字符。文本的第一部分左移,最后一个字符取自假想的圆形源文本。让我们跟踪假想的圆形源文本中的位置:

size_t position = 0; // start at character zero of word

现在

while (1)
{
// shift the buffer
for (size_t i = 0u; i < (buffsize - 1u); i++)
buffer[i] = buffer[i + 1u];
// fill in the last character
buffer[buffsize - 1u] = position < wordsize ? word[position] : ' ';
// increment the position in the imaginary circular source text
position = (position + 1u) % icstsize;
}

关于c - 从右到左在 C 中的数组中滚动一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48331360/

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