使用 C 将字符串中每个字符的位置从其当前位置循环移动到它的右边
Using C move the position of each character in a string to it's right circularly from it's current position
我必须在用户输入的字符串中一次移动一个字符。
在每次迭代中,程序将字符从当前位置向右循环移动。即第一个字符移到第二位,第二个字符移到第三位,依此类推。最后一个字符移到第一位。移动字符后,程序还必须在每次迭代中打印新字符串。继续迭代,直到返回原始字符串。
例如用户输入字符串:'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]);
}
声明一个 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"):
}
可能的解决方案:
从示例输出来看,您似乎需要像 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");
}
}
希望这有助于您理解解决方案背后的逻辑。
我必须在用户输入的字符串中一次移动一个字符。 在每次迭代中,程序将字符从当前位置向右循环移动。即第一个字符移到第二位,第二个字符移到第三位,依此类推。最后一个字符移到第一位。移动字符后,程序还必须在每次迭代中打印新字符串。继续迭代,直到返回原始字符串。
例如用户输入字符串:'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]);
}
声明一个 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"):
}
可能的解决方案:
从示例输出来看,您似乎需要像 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");
}
}
希望这有助于您理解解决方案背后的逻辑。