Для последовательных изменений, я хотел бы сделать это:
- Поместите их в
Array
слов по split(' ')
- Генерирует случайное значение от 0 до длины
Array
минус 5 по Random
- Поместите их в предложение, дает некоторые пробелы.
VB версия + тестирование результат
(Это может быть то, что вы больше заинтересованы в)
Imports System
Imports System.Text
Public Module Module1
Public Sub Main()
Dim str As String = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
Console.WriteLine(GrabRandSequence(str))
Console.WriteLine(GrabRandSequence(str))
Console.WriteLine(GrabRandSequence(str))
Console.ReadKey()
End Sub
Public Function GrabRandSequence(inputstr As String)
Try
Dim words As String() = inputstr.Split(New Char() {" "c})
Dim index As Integer
index = CInt(Math.Floor((words.Length - 5) * Rnd()))
Return [String].Join(" ", words, index, 5)
Catch e As Exception
Return e.ToString()
End Try
End Function
End Module
Результат
C# версия
string[] words = input.Split(' '); //Read 1.
int val = (new Random()).Next(0, words.Length - 5); //Read 2.
string result = string.Join(" ", words, val, 5); //Read 3. improved by Enigmativy's suggestion
Дополнительные попробовать
Для случайных изменений, я хотел бы сделать это:
- очистить все ненужные символы (.И т.д.)
- поместить их в
List
по LINQ
split(' ')
- Выберите
Distinct
среди них LINQ
(по желанию, чтобы избежать результат, как Lorem Lorem Lorem Lorem Lorem
)
- Генерировать 5 различных случайных значений от 0 до размера
List
от Random
(повтор выбор, когда не отчетливо)
- Подберите слова в соответствии с произвольными значениями из
List
- Поместите их в предложение, задайте несколько пробелов.
Предупреждение: предложение не имеет смысла вообще!
C# версии (только)
string input = "the input sentence, blabla";
input = input.Replace(",","").Replace(".",""); //Read 1. add as many replace as you want
List<string> words = input.Split(' ').Distinct.ToList(); //Read 2. and 3.
Random rand = new Random();
List<int> vals = new List<int>();
do { //Read 4.
int val = rand.Next(0, words.Count);
if (!vals.Contains(val))
vals.Add(val);
} while (vals.Count < 5);
string result = "";
for (int i = 0; i < 5; ++i)
result += words[vals[i]] + (i == 4 ? "" : " "); //read 5. and 6.
Ваш результат находится в result
Там нет необходимости удалять лишние символы. Задача состояла в том, чтобы возвращать последовательные слова из исходного текста, а не 5 отдельных случайных слов. И объединение строк с '+ (i == 4?" ":" ") Является странным, учитывая, что' result = String.Join ("", words); 'было бы достаточно. – Enigmativity