【问题标题】:Using C move the position of each character in a string to it's right circularly from it's current position使用 C 将字符串中每个字符的位置从当前位置循环向右移动
【发布时间】:2015-12-27 16:04:18
【问题描述】:

我必须在用户输入的字符串中一次移动一个字符。 在每次迭代中,程序将字符从当前位置循环向右移动。即第一个字符移到第二位,第二个字符移到第三位,依此类推。最后一个字符移动到第 1 位。移动字符后,程序还必须在每次迭代中打印新字符串。迭代一直持续到原始字符串被取回。

例如用户输入字符串:'cat'

第一次迭代后字符串为:'tca'

第二次迭代后字符串为:'atc'

第三次迭代:'cat'(与程序完成相同)

我写了一个反转整个字符串的代码。但是,我真的不知道如何一次移动一个角色。代码如下:

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

main ()
{
    char  word[20];
    printf("enter word:");
    int d,i;
    scanf("%s",&word);
    d = strlen(word);

    for(i=d-1; i >= 0; i--)
        printf("%c",word[i]);
}

【问题讨论】:

  • 欢迎来到 SO。似乎你在混淆一些东西,你展示的是 C 而不是 C++。请编辑问题并更改标签。

标签: c string reverse


【解决方案1】:

声明一个 var j 并将你的 for 循环替换为:

   for (i = d-1; i >=0; i--) {
        j = i;
        printf("%c",word[j]);
        j = (j + 1) % d;
        while ( j != i) {
            printf("%c",word[j]);
            j = (j + 1) % d;
        }
        printf ("\n"):
    }

【讨论】:

    【解决方案2】:

    可能的解决方案:

    从示例输出看来,您需要像circular array 一样访问字符串。在这种情况下,您可能需要每次从索引 (size - move_number) 中迭代字符串,然后通过像循环数组一样访问它们来打印索引。

    更新代码:

    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    void main()
    
    {
        char  word[20];
        printf("enter word:");
        int d, i;
        scanf("%s", &word);
        d = strlen(word);
    
        for (i = d - 1; i >= 0; i--) 
        {
            int j = i;
            do
            {
                printf("%c", word[j]);   //Printing each index
                j = (j + 1) % d;        //computing the next index to print
            }
            while (j != i);             //Condition which determines that whole string is traversed
            printf("\n");
        }
    }
    

    希望这有助于您理解解决方案背后的逻辑。

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2018-12-15
      • 2013-09-11
      • 2015-05-22
      • 1970-01-01
      相关资源
      最近更新 更多