0

在主要学习 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)
  {


  }
}

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

4

1 回答 1

-2

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

(请注意,scanf()&%s将读取一个字符串,直到在按 Enter 后找到一个空格。因此,'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()循环中不断调用它们。

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

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
}

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

干杯

于 2015-03-04T16:30:04.213 回答