【问题标题】:Scramble a String Using C使用 C 对字符串进行加扰
【发布时间】:2015-05-05 17:26:47
【问题描述】:

在主要学习 Java 之后,我本学期刚开始学习 C,我被要求创建一个程序,允许用户输入字符串,然后打乱字符串中的字母。

#include <stdio.h> //Alows input/output operations
#include <stdlib.h> //Standard utility operations

int main(int argc, char *argv[]) //Main method
{
  printf("------------------------\n");
  printf("WELCOME TO THE SCRAMBLER\n");
  printf("------------------------\n\n");

  char userString[50]; //Declaring the user string 
  printf("Please input a String :> "); //Iforms the user to enter a string
  scanf("%s", userString); //Allows the user to enter in a string

  char targetLetter[2]; //Declaring the target letter
  char replaceLetter[2]; //Declaring the replace letter

  while(1)
  {


  }
}

这是我目前所拥有的,我只需要有关如何实际打乱字符串的帮助/建议。用户应该能够随意加扰字符串,直到他们输入特定字符,然后程序终止。提前感谢您的帮助!

【问题讨论】:

  • 如果打乱是指将字母随机排列,您可以使用fisher-yates shuffle。
  • @indiv 感谢您的回复。我的目标是让用户可以从他们创建的字符串中选择一个字母并将其替换为另一个字母/字符。
  • This 你会感兴趣的。

标签: c string scramble


【解决方案1】:

您要做的第一件事是考虑一个简单的算法来打乱字符串。

(注意scanf() & %s 会读取一个字符串,直到找到一个空格,然后按回车键。因此,'hello world' 将只是'hello'。如果你需要获取偶数,请改用gets()空格字符)。

一个简单的随机播放函数可以是:

void mix (char * string) {
    //Get string length
    int len = strlen(string);
    int i;

    char tmp;

    for (i = 0; i < len / 2; i++) {
        //Loop every char till the middle of the string
        //Save the current char
        tmp = string[i];
        //Put in this position the opposite char in the string
        string[i] = string[len - i];
        //Replace the opposite char
        string[len - i] = tmp;
    }
}

//If you input hello you should get olleh

但这并不是您真正想要的,但我建议您创建两三个这样的函数,并在 while() 循环中一个一个地调用它们。

在循环重新启动之前,只需使用 scanf() 向用户询问char。

while 循环应该是这样的:

while (char != 'a') {
  //Mix the string
  mix_1();
  mix_2();
  mix_3();
  //Ask char again
  scanf("%c",&char);
  //Loop goes on till char != a
}

希望这会有所帮助。在这种情况下,对这个答案进行简单的投票对我真的很有帮助。

干杯

【讨论】:

  • 不,请改用fgets()!
  • 即使它发出警告,为了他的目的,他绝对应该没问题。无论如何感谢您的提示
  • 问题是他使用了一个不推荐使用的函数,而不是一个他可以在未来使用的安全函数。
  • @FoxNos: gets() 在&lt;stdio.h&gt; 中声明,而不是在&lt;string.h&gt; 中声明。除非您的编译器符合 2011 ISO C 标准;然后gets() 没有在任何地方声明(它被从语言中删除,因为它本质上是不安全的)。我敦促您停止使用gets,并且请停止建议其他人使用它。
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 2012-03-23
  • 2012-10-25
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 1970-01-01
相关资源
最近更新 更多