Solved

Extracting "tokens" from a string

Posted on 2012-03-13
4
277 Views
Last Modified: 2012-03-13
Hey guys,

I'm a little stumped on the best way to approach this. Let's say I have a string like this:

{hello|hi|hey|what's up} it's {great|awesome|wonderful} to hear from you! When you get a {chance|minute|second} please read my {article|review}. Thanks!

Open in new window


What I'd like to do is take this string as input and output a string with a random selection of each token. So for example:

hey it's wonderful to hear from you! When you get a second please read my review. Thanks!

Open in new window


I hope this makes sense. How would you guys approach this?
0
Comment
Question by:mcainc
4 Comments
 
LVL 1

Expert Comment

by:Turkey1974
ID: 37715570
Here's an example I found for C:
#include <stdio.h>
#include <stdlib.h>
int main() {
     const char *messages[] = {
         "Hello!",
         "How are you?",
         "Good stuff!"
     };
     const size_t messages_count = sizeof(messages) / sizeof(messages[0]);
     char input[64];
     while (1) {
         scanf("%63s", input);
         printf("%s\n", messages[rand() % messages_count]);
     }
     return 0;
 }



********************************************************************
Here's a batch example that randomizes the token # 1-9, hence the need for 9 greetings:

create a text file called subA.txt and add 9 comma delimited greetings to the first line:
Hello,Hi,Hey,What's up,Howdy,Hello,Hi,Hey,What's up

In a batch file use:

@echo off
for /f "tokens=%random:~-1% delims=," %%i IN (suba.txt) do @echo %%i it's wonderful to hear from you!
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 37715895
I'm sure it could be done more elegantly with Regular Expressions but I suck at those.

Instead, here's an old school low level approach:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Sentence sentence;

        private void Form1_Load(object sender, EventArgs e)
        {
            string template = "{hello|hi|hey|what's up} it's {great|awesome|wonderful} to hear from you! When you get a {chance|minute|second} please read my {article|review}. Thanks!";
            sentence = new Sentence(template);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.sentence != null)
            {
                this.label1.Text = this.sentence.template;
                this.label2.Text = this.sentence.RandomSentence();
            }
        }


    }

    public class Sentence
    {

        private Random R = new Random();
        private List<string[]> tokens = new List<string[]>();
        private string _tokenizedSentence = "";
       
        private string _template;
        public string template
        {
            get { return _template; }
        }

        public Sentence(string template)
        {
            this.SetTemplate(template);
        }

        public void SetTemplate(string template)
        {
            this._template = template;

            bool InToken = false;
            string curChar;
            string curToken = "";
            string tokenizedSentence = "";
            for (int i = 0; i < template.Length; i++)
            {
                curChar = template.Substring(i, 1);
                switch (curChar)
                {
                    case "{":
                        if (!InToken)
                        {
                            InToken = true;
                            curToken = "";
                            tokenizedSentence = tokenizedSentence + "|";
                        }
                        else
                        {
                            // malformed template!
                        }
                        break;

                    case "}":
                        if (InToken)
                        {
                            InToken = false;
                            tokens.Add(curToken.Split("|".ToCharArray()));
                        }
                        else
                        {
                            // malformed template!
                        }
                        break;

                    default:
                        if (InToken)
                        {
                            curToken = curToken + curChar;
                        }
                        else
                        {
                            tokenizedSentence = tokenizedSentence + curChar;
                        }
                        break;
                }
            }
            if (!InToken)
            {
                this._tokenizedSentence = tokenizedSentence;
            }
            else
            {
                // malformed template!
            }
        }

        public string RandomSentence()
        {
            string output = "";
            string curChar = "";
            int tokenCounter = 0;
            for (int i = 0; i < this._tokenizedSentence.Length; i++)
            {
                curChar = this._tokenizedSentence.Substring(i, 1);
                switch (curChar)
                {
                    case "|":
                        if (tokenCounter < this.tokens.Count)
                        {
                            string[] curTokens = this.tokens[tokenCounter];
                            output = output + curTokens[this.R.Next(curTokens.Length)];
                            tokenCounter++;
                        }
                        else
                        {
                            // malformed template!
                        }
                        break;

                    default:
                        output = output + curChar;
                        break;
                }
            }
            return output;
        }

    }
}

Open in new window

0
 

Author Closing Comment

by:mcainc
ID: 37716888
This is perfect!
0
 
LVL 40
ID: 37716891
I had fun with that one, thanks.

Here is the result:

Dim salutation() As String = {"hello", "hi", "hey", "what's up"}
Dim superlative() As String = {"great", "awesome", "wonderful"}
Dim timing() As String = {"chance", "minute", "second"}
Dim source() As String = {"article", "review"}
Dim rnd As New Random(CInt(Date.Now.Millisecond))

MessageBox.Show(String.Format("{0} it's {1} to hear from you! When you get a {2} please read my {3}. Thanks!", 
      salutation(rnd.Next(4)), 
      superlative(rnd.Next(3)), 
      timing(rnd.Next(3)), 
      source(rnd.Next(2))))

Open in new window


Sorry for the VB, I am coaching one of my clients at his place today, and he does not have C# installed and he is coming back so I have to leave. Should be easy to convert. The Dim instructions are declarations for auto-initializing arrays. You will have to change () for [] when using the arrays. The
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now