Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String tokens in .NET

Tags:

c#

.net

vb.net

I am writing 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.

like image 290
julio Avatar asked Jun 01 '10 19:06

julio


People also ask

What are strings in tokens?

String tokenization is a process where a string is broken into several parts. Each part is called a token. For example, if “I am going” is a string, the discrete parts—such as “I”, “am”, and “going”—are the tokens. Java provides ready classes and methods to implement the tokenization process.

What is token used for in C#?

Token-based authentication is a process where the client application first sends a request to Authentication server with a valid credentials. The Authentication server sends an Access token to the client as a response. This token contains enough data to identify a particular user and it has an expiry time.

What is string tokenization in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.

How do you split a character in a string in C#?

Split(char[]) Method This method is used to splits a string into substrings that are based on the characters in an array. Syntax: public String[] Split(char[] separator); Here, separator is a character array that delimits the substrings in this string, an empty array that contains no delimiters, or null.


2 Answers

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)
like image 196
Mark Byers Avatar answered Nov 09 '22 21:11

Mark Byers


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);
    }
}
like image 22
Dr. Wily's Apprentice Avatar answered Nov 09 '22 21:11

Dr. Wily's Apprentice