如何阻止字符串重复?如何传递方法三个随机字符串消息?

时间:2014-09-18 18:13:27

标签: c# string random generator

class Program
{
    static void Main(string[] args)
    {
        //array of strings
        string[] phrases = { "Buy it today", "You won't regret your purchase", "Satisfaction is guaranteed", "Purchase of a lifetime", "Such a great deal", "Limited time only" };
        Random r = new Random();
        string random = phrases[r.Next(0, 5)];
        string random2 = phrases[r.Next(0, 5)];
        string random3 = phrases[r.Next(0, 5)];

        RanStrings(random, random2, random3);
    }

    private static void RanStrings(string random, string random2, string random3)
    {
        Console.WriteLine(random);
        Console.WriteLine(random2);
        Console.WriteLine(random3);
    }
}

2 个答案:

答案 0 :(得分:0)

你的问题不是很清楚,但根据我的理解,你需要一种检查方法的方法,如:

   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Threading.Tasks;

namespace FormLetter
{
    class Program
    {

        static void Main(string[] args)
        {
            string random="";
            string random2 ="";
            string random3 ="";
         do{
            //array of strings
            string[] phrases = { "Buy it today", "You won't regret your purchase", "Satisfaction is                   guaranteed", "Purchase of a lifetime", "Such a great deal", "Limited time only" };
            Random r = new Random();
            random = phrases[r.Next(0, 5)];
            random2 = phrases[r.Next(0, 5)];
            random3 = phrases[r.Next(0, 5)];
           }while(compareStrings(random,random2, random3))

            RanStrings(random, random2, random3);
        }

        private static void RanStrings(string random, string random2, string random3)
        {
            Console.WriteLine(random);
            Console.WriteLine(random2);
            Console.WriteLine(random3);
        }
        private static bool compareStrings(string random, string random2, string random3)
        {
            //put here your comparison code
            if (there is equality between 2 strings passed in argument)
            return true;
            else  return false;
        }
    }
}

答案 1 :(得分:0)

听起来你想" shuffle"字符串而不是随意挑选一个(基本上随机选择而不替换)。如果是这种情况,只需使用带有随机数的OrderBy

Random r = new Random();

string[] phrases = { "Buy it today", "You won't regret your purchase", "Satisfaction is guaranteed", "Purchase of a lifetime", "Such a great deal", "Limited time only" };
phrases = phrases.OrderBy(s => r.Next()).ToArray();

// now just take the "first" 3    

RanStrings(phrases[0], phrases[1], phrases[2]);