c - C 编程中对数组中的字符进行打乱

标签 c arrays random character shuffle

使用在线教程,我尝试对数组中的字符进行随机排列。我使用的教程使用整数,也不包含任何用户输入,但是当我尝试复制它并将其更改为我在下面编写的代码中执行的操作时,有些东西不起作用。

根本没有错误消息。当我运行该程序时,它仅提示用户输入一个单词,然后结束。

以防万一您无法理解我想要从代码中获得什么,我希望用户能够插入一个单词,然后在末尾打印“随机排列”的单词。 (例如,Hello > elHol)

我仍然是一个非常新的程序员,并且总体上对这个主题感到非常困难,所以请理解您可能会遇到的我所犯的任何“愚蠢”错误。

预先感谢您的帮助!

#include <stdio.h>
#include <time.h>

int main ()
{
    char word[15];
    int i,length,j, temp;

     srand(time(NULL));

     printf("Insert word\n");
     scanf("%s", word);

     for(i=0; word[i] != '\0'; )
     {
        i = i + 1;
    }

     i = length;

     for(i = 0; i < length; i++)
    {
        j = (rand()%length);
        temp = word[i];
        word[i] = word[j];
        word[j] = temp;
    }

    for(i=0; i<length; i++)
    {
         printf("%c", word[i]);
    }
}

最佳答案

欢迎;)。除了其他工程师对您的问题的解决方案之外,我还修改了您的代码,不使用临时变量进行交换。[既然您提到了新程序员,我觉得这应该在一定程度上有所帮助。 ;)]

查看下面的源代码。

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

int main ()
{
    char word[15];
    int i,length,j, temp;

     srand(time(NULL));

     printf("Insert word\n");
     scanf("%s", word);

     for(length=0; word[length++] != '\0';);
     for(i = 0; i < length; i++)
    {
        j = (rand()%length);
        word[i] = word[i] ^ word[j];
        word[j] = word[i] ^ word[j];
        word[i] = word[i] ^ word[j];
    }

    for(i=0; i<length; i++)
    {
         printf("%c", word[i]);
    }
}

关于c - C 编程中对数组中的字符进行打乱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27497346/

相关文章:

c - 如何在C中返回指向字符串数组的指针

c++ - 驻留内存增加,而 valgrind 未显示任何泄漏

javascript - 数组中的字符串在 HTML 中不显示为字符串

c - 神秘变化的结构成员(涉及指针):

c++ - 尝试生成随机变量时获取 "-nan(ind)"

java - 使用 import java.util.Random; nextInt 和用户输入

c - UART 接收中断启用但没有 ISR?

c - 使用 waitpid() 的例子?

arrays - 如何在散列中插入散列的散列?

java - 如何从数组生成 3 个随机值