将字符串随机插入另一个字符串

时间:2015-11-06 04:31:13

标签: vb.net string random

有没有人有一个很好的方法可以将列表中的所有项目随机插入另一个字符串?例如,如果我有段落的文本,我想在句子后随机插入网址。 Url存储在列表对象中。我该怎么做呢?我以为我可以计算句号和其他标点符号的数量,但我还要以某种方式存储每个句点的位置。如果有人能指出我正确的方向,我会很感激。

我认为逻辑如下:

计算期间, 将期间索引存储在列表中, 从列表中获取随机索引, 通过向索引添加1来在该索引之后插入文本

2 个答案:

答案 0 :(得分:1)

这对你有用吗?

var rnd = new Random();
var urls = new [] { "www.a.com", "www.b.com" };
var text = "I like apples. I like bananas.";

var query =
    from t in text.Split(new [] { '.' }, StringSplitOptions.RemoveEmptyEntries)
    from x in new [] { t, ". ", urls[rnd.Next(urls.Length)] }
    select x;

var result = String.Join("", query);
  我喜欢苹果。 www.b.com我喜欢香蕉。 www.a.com

答案 1 :(得分:0)

你走了。

Module Module1
    ' String to insert into
    Const target As String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vel posuere neque, quis suscipit diam. Proin congue dapibus elit, ut tempus leo. Suspendisse suscipit mi quis purus laoreet facilisis. Sed eget arcu eu risus sodales posuere. Nulla ut nulla urna. Quisque eu eleifend metus. Mauris suscipit rhoncus eros at ultrices. Cras sodales facilisis mauris, vitae condimentum mi tempus a. Suspendisse hendrerit, arcu sit amet viverra placerat, eros quam venenatis enim, id tincidunt felis mauris id augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur ac ullamcorper sem, sed porta orci. Praesent euismod, ipsum et sagittis gravida, purus ipsum venenatis ipsum, quis congue risus erat in magna. Donec nec elit ut velit faucibus efficitur. Donec facilisis, tellus et volutpat hendrerit, dui sem pulvinar lectus, sit amet fringilla sem mi eget elit."
    ' Urls to insert
    Private injections As String() = New String() {"http://lorempixel.com/output/cats-q-c-640-480-1.jpg", "http://lorempixel.com/output/cats-q-c-640-480-2.jpg", "http://lorempixel.com/output/cats-q-c-640-480-3.jpg", "http://lorempixel.com/output/cats-q-c-640-480-4.jpg"}

    Sub Main()
        Dim sentence As New System.Text.RegularExpressions.Regex("[^.!?]+[.!?]")
        Dim result As New System.Text.StringBuilder()
        Dim n As Integer = injections.Count()
        ' Break sentence at punctuation.
        For Each m As System.Text.RegularExpressions.Match In sentence.Matches(target)
            ' Get index of one of our injection strings at random.
            Dim i As Integer = CInt(Math.Ceiling(Rnd() * n)) - 1
            result.Append(m).Append(injections(i))
        Next
        Console.WriteLine(result.ToString())
        Console.ReadKey()
    End Sub

End Module