Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Extracting "tokens" from a string

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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
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 course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

597 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