?
Solved

Extracting "tokens" from a string

Posted on 2012-03-13
4
Medium Priority
?
284 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 2000 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

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Suggested Courses

801 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