C# 随机选取中文数组元素生成新数组
C# 从中文数组中随机选取元素生成新数组
假设我们有一个长度不固定的中文字符串数组,需要从中随机选取 15 个元素组成一个新的数组。
1. 定义中文字符串数组:
string[] chineseArray = {'你好', '世界', '北京', '上海', '广州', '深圳', '纽约', '伦敦', '巴黎', '东京', '首尔', '悉尼'};
2. 使用 Random 类随机选取元素:
// 创建一个Random对象
Random random = new Random();
// 新数组的长度
int length = 15;
// 创建一个新数组
string[] newArray = new string[length];
// 从原数组中随机选取元素
for (int i = 0; i < length; i++)
{
// 生成一个随机索引
int index = random.Next(chineseArray.Length);
// 将选中的元素添加到新数组中
newArray[i] = chineseArray[index];
}
3. 获取新数组:
最终,我们得到了一个长度为 15 的新数组 newArray,其中的元素是随机选取的原数组 chineseArray 中的元素。
代码示例:
using System;
public class Program
{
public static void Main(string[] args)
{
// 定义中文字符串数组
string[] chineseArray = {'你好', '世界', '北京', '上海', '广州', '深圳', '纽约', '伦敦', '巴黎', '东京', '首尔', '悉尼'};
// 创建一个Random对象
Random random = new Random();
// 新数组的长度
int length = 15;
// 创建一个新数组
string[] newArray = new string[length];
// 从原数组中随机选取元素
for (int i = 0; i < length; i++)
{
// 生成一个随机索引
int index = random.Next(chineseArray.Length);
// 将选中的元素添加到新数组中
newArray[i] = chineseArray[index];
}
// 打印新数组
Console.WriteLine("新数组:");
foreach (string item in newArray)
{
Console.WriteLine(item);
}
}
}
原文地址: http://www.cveoy.top/t/topic/oUCE 著作权归作者所有。请勿转载和采集!