Solved

Extracting "tokens" from a string

Posted on 2012-03-13
4
282 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 86

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

Raise the IQ of Your IT Alerts

From IT major incidents to manufacturing line slowdowns, every business process generates insights that need to reach the people required to take action. You need a platform that integrates with your business tools to create fully enabled DevOps toolchains.

You need xMatters.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

689 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