Solved

Extracting "tokens" from a string

Posted on 2012-03-13
4
278 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

920 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

13 Experts available now in Live!

Get 1:1 Help Now