开发者

String tokens in .NET

I am writi开发者_开发知识库ng a app in .NET which will generate random text based on some input. So if I have text like "I love your {lovely|nice|great} dress" I want to choose randomly from lovely/nice/great and use that in text. Any suggestions in C# or VB.NET are welcome.


You could do it using a regex to make a replacement for each {...}. The Regex.Replace function can take a MatchEvaluator which can do the logic for selecting a random value from the choices:

Random random = new Random();
string s = "I love your {lovely|nice|great} dress";
s = Regex.Replace(s, @"\{(.*?)\}", match => {
    string[] options = match.Groups[1].Value.Split('|');
    int index = random.Next(options.Length);
    return options[index];
});
Console.WriteLine(s);

Example output:

I love your lovely dress

Update: Translated to VB.NET automatically using .NET Reflector:

Dim random As New Random
Dim s As String = "I love your {lovely|nice|great} dress"
s = Regex.Replace(s, "\{(.*?)\}", Function (ByVal match As Match) 
    Dim options As String() = match.Groups.Item(1).Value.Split(New Char() { "|"c })
    Dim index As Integer = random.Next(options.Length)
    Return options(index)
End Function)


This may be a bit of an abuse of the custom formatting functionality available through the ICustomFormatter and IFormatProvider interfaces, but you could do something like this:

public class ListSelectionFormatter : IFormatProvider, ICustomFormatter
{
    #region IFormatProvider Members

    public object GetFormat(Type formatType)
    {
        if (typeof(ICustomFormatter).IsAssignableFrom(formatType))
            return this;
        else
            return null;
    }

    #endregion

    #region ICustomFormatter Members

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        string[] values = format.Split('|');

        if (values == null || values.Length == 0)
            throw new FormatException("The format is invalid.  At least one value must be specified.");
        if (arg is int)
            return values[(int)arg];
        else if (arg is Random)
            return values[(arg as Random).Next(values.Length)];
        else if (arg is ISelectionPicker)
            return (arg as ISelectionPicker).Pick(values);
        else
            throw new FormatException("The argument is invalid.");
    }

    #endregion
}

public interface ISelectionPicker
{
    string Pick(string[] values);
}

public class RandomSelectionPicker : ISelectionPicker
{
    Random rng = new Random();

    public string Pick(string[] values)
    {
        // use whatever logic is desired here to choose the correct value
        return values[rng.Next(values.Length)];
    }
}

class Stuff
{
    public static void DoStuff()
    {
        RandomSelectionPicker picker = new RandomSelectionPicker();
        string result = string.Format(new ListSelectionFormatter(), "I am feeling {0:funky|great|lousy}.  I should eat {1:a banana|cereal|cardboard}.", picker, picker);
    }
}


String.Format("static text {0} more text {1}", randomChoice0, randomChoice1);


write a simple parser that will get the information in the braces, split it with string.Split , get a random index for that array and build up the string again.

use the StringBuilder for building the result due to performance issues with other stringoperations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜