.NET中的字符串标记

时间:2010-06-01 19:31:46

标签: c# .net vb.net

我正在用.NET编写一个应用程序,它将根据一些输入生成随机文本。因此,如果我有"I love your {lovely|nice|great} dress"这样的文字,我想从lovely/nice/great中随机选择并在文本中使用它。欢迎使用C#或VB.NET中的任何建议。

4 个答案:

答案 0 :(得分:8)

您可以使用正则表达式替换每个{...}Regex.Replace函数可以使用MatchEvaluator来执行从选项中选择随机值的逻辑:

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);

示例输出:

I love your lovely dress

更新:使用.NET Reflector自动转换为VB.NET:

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)

答案 1 :(得分:2)

这可能有点滥用ICustomFormatter和IFormatProvider接口提供的自定义格式化功能,但您可以这样做:

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);
    }
}

答案 2 :(得分:1)

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

答案 3 :(得分:0)

编写一个简单的解析器,它将获取大括号中的信息,用string.Split拆分,获取该数组的随机索引并再次构建字符串。

由于其他字符串操作的性能问题,使用StringBuilder来构建结果。