Is there an elegant work around to concatenation?

I am writing a mad libs program for fun and to just program something. The program itself is pretty straight forward, but I find myself resorting to several concatenations due to the nature of the game where you place user given words into a sentence. Is there an elegant work around to resort to less concatenations or even eliminate them for something more efficient? I know in the end it will make no difference if I use concatenations or not, but I am curious if there is a more elegant way to write this program.

Update: I am using java, but if there is a general solution to escaping concatenation that would be appreciated too.

-------------Problems Reply------------

One solution might be to write out your whole mad libs file and put in special tokens that need to be replaced by the words that are chosen.

You just bought a brand new ${NOUN1}, and it is going to ${VERB1} you.

Then you can use for example: String.replace("${NOUN1}", noun1) for all the words.

Which language are you using?

Most high level langauges will have something similar to:

String.Format("{0} {1} {2} {3}", word1, word2, word3, word4);

There are two ways I can see you entirely avoiding concatenation in your game:

  1. Store the story template as as a collection of tokens: immutable parts and word placeholders. Then loop through the collection outputting immutable parts and user words instead of word placeholders.
  2. Write custom print class that will loop through the template string using charAt and output words instead of word placeholders.

Rather than calling String.replace for each word or constantly appending to a StringBuilder, you could put the words in an ordered array and use String.format ( in jdk 1.5 or newer ) or MessageFormat.format in jdk 1.4. Unfortunately the pattern formats for the two are different.

String myPattern = "My %s eats your %s";
// get values from the user here
String result = String.format( myPattern, (Object[])myArray );

or

String myPattern = "My {0} eats your {1}";
// get values from the user here
String result = MessageFormat.format( myPattern, (Object[])myArray );

Here is a complete program that fills in the string with values from the command line.

public class Format
{
public static void main( String[] args )
{
String pattern = "My %s eats your %s";
System.out.println( String.format( pattern, (Object[])args ));
}
}

There're two aspects of your question.

First, you might wish to avoid using concatenations directly in your code. Then you can use some string-formatting routine from the runtime. This won't skip concatenations, but will move them from your code to the runtime.

Second, you may want to do concatenations more efficently. That's another story. The most important thing here is to preallocate the big enough buffer for the concatenated string, since memory reallocations are quite expensive. Copying substrings into the result strings are usually less expensive and are a necessary evil.

Nothing comes to my mind in terms of a general way to avoid concatenation. What you could do is to write yourself some kind of helper class which simplifies the job of concatenation for you. A suggestion I would like to give you however is to not directly concatenate strings as

String x = "Hi";
String y = x + " there!";

The implementation of string concatenation is quite slow in Java, so it's a better practice to use StringBuffer instead, especially if you do a lot of concatenations:

StringBuffer myStringBuffer = new StringBuffer();
myStringBuffer.append("Hi");
myStringBuffer.append(" there!");

Something like this. I didn't check this now in a compiler, but I'm sure you can figure it out yourself.

Not sure about Java but in some other languages such as PHP and Javascript creating an array and joining all of its elements can be faster.

Javascript example:

var str = str1 + str2 + str3 + "str4" + str5 + "str6" + str7;
var str = [str1, str2, str3, "str4", str5, "str6", str7].join("");

PHP example:

$str = $str1 . $str2 . $str3 . "str4" . $str5 . "str6" . $str7;
$str = implode("", array($str1, $str2, $str3, "str4", $str5, "str6", $str7));

This method is best if you want to put a delimiter between each string in which case it will not only be faster but more compact and readable.

By 'avoiding concatenation' I assume you mean allocating the space for the new string and assigning it? If you're on .NET then a StringBuilder should help some I think.

If you have a String an need to modify it very often, using a char[] array and creating a String when done modifying it might do the trick.

It's certainly possible to do this without concatenation if you want to. Although it's probably not very worthwhile.

It partly depends on where you're going to display the result. If it's on the web or the console, then you can write the result directly to an output stream.

So for example, if your template was something like "the %001 jumped out of the %002" you could:

1) scan the string to find where the variables are. 2) break the string into a list of components "the","jumped out of the", in this case 3) loop through the elements of your list and the results and dump them to output with something like this:

PrintStream = //get output from somewhere
for(int i = 0; i < pieces.size()-1 ; i++){
ps.print(peices.get(i));
ps.print(answers.get(i));
}
ps.print(pieces.get(pieces.size()-1));//last one

Now. I don't know if you would call that 'elegant' or not. It would probably be kind of fast. Like I said, maybe appropriate if this was a web service and it became super popular, etc.

If this is a GUI app, you could write code to draw the strings separately, but that would probably take more time then concatenation.

but one thing you could do is use a ByteArrayOutputStream and pre-allocate enough space so that it could contain the filled out madlib without making additional allocations. That would be pretty quick as well.

Why do you want to avoid concatenation if its for cleanliness try lining it up nicely and it may end up looking surprisingly good.Even if you are worried about performance you may not need to use string builder, I believe that if you do a bunch of concatenations simply(ie "fdsfsd" + var1 +var2 +"dsfsdf" +"tyhty" it compiles to the same thing as string builder(effectively the same and looks cleaner). String Builder does make sense if you are concating a ton of stuff in a loop or with a complex flow.

Category:java Views:0 Time:2009-03-16

Related post

  • How to get values in an array this way with PHP? 2009-11-20

    From: $arr = array(array('key1'=>'A',...),array('key1'=>'B',...)); to: array('A','B',..); --------------Solutions------------- Relatively simple conversion by looping: $newArray = array() foreach ($arr as $a) { foreach ($a as $key => $value)

  • How to elegantly compute the anagram signature of a word in ruby? 2008-12-30

    Arising out of this question, I'm looking for an elegant (ruby) way to compute the word signature suggested in this answer. The idea suggested is to sort the letters in the word, and also run length encode repeated letters. So, for example "mississip

  • What are some elegant features or uses of Perl? 2009-03-13

    What? Perl Beautiful? Elegant? He must be joking! It's true, there's some ugly Perl out there. And by some, I mean lots. We've all seen it. Well duh, it's symbol soup. Isn't it? Yes there are symbols. Just like 'math' has 'symbols'. It's just that we

  • Inserting a Java string in another string without concatenation? 2009-04-21

    Is there a more elegant way of doing this in Java? String value1 = "Testing"; String test = "text goes here " + value1 + " more text"; Is it possible to put the variable directly in the string and have its value evaluated? --------------Solutions----

  • Elegant way building url request with parameters 2009-11-19

    There must me a more elegant way to build a URL with parameters in .NET then for example Response.Write("<a href=HeadOfMarketView.aspx"+Session["HOM"] != null ? Session["HOM"]+">Head of Market</a> / ") I mean the concatenation of strings

  • Concatenating PDFs in PHP 2009-11-23

    I've got a grip of PDFs that I need to combine into one using PHP. Googling around gives me very little that seems like a reasonable solution. The best thing I can find is to use exec() and pdftk but that's just ugly. Does anyone know of a more elega

  • Need a Concatenating VBA code to prevent memory issue workaround 2009-12-06

    My set up: Have 50,000 rows of data. ( My row count will increase in the future. So might as well say I have a full worksheet of 64000+ rows.) All Data is TEXT, no formulas, etc. Column A is open Columns B thru AC contain the Data that needs to be co

  • an elegant way to build the string in c# 2010-01-06

    string to build up using keyvaluepair is like this: "name1=v1&name2=v2&name3=v3" what i am doing: var sb = new StringBuilder(); foreach (var name in nameValues) { sb.AppendFormat("{0}={1}&", name.Key, name.Value); } //remove last '&'

  • How to elegantly write a SQL ORDER BY (which is invalid in inline query) but required for aggregate GROUP BY? 2010-01-19

    I have a simple query that runs in SQL 2008 and uses a custom CLR aggregate function, dbo.string_concat which aggregates a collection of strings. I require the comments ordered sequentially hence the ORDER BY requirement. The query I have has an awfu

  • Elegant solution for line-breaks (PHP) 2010-04-28

    $var = "Hi there"."<br/>"."Welcome to my website"."<br/>;" echo $var; Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol so something thats more readable and elegant to use? Thanks --

  • convert array of objects to concatenated string 2010-05-12

    if i have: List<Car> where car is: public class Car { public int Year; public string Name; } and i want to take this array and create a concatenated string by "," so it would return: "Toyota, Ford, Chevy" i can do it manually like this: private

  • What's so bad about building XML with string concatenation? 2010-06-14

    In the thread What’s your favorite “programmer ignorance” pet peeve?, the following answer appears, with a large amount of upvotes: Programmers who build XML using string concatenation. My question is, why is building XML via string concatenation (su

  • Is there a more elegant way to act on the first and last items in a foreach enumeration than count++? 2010-06-16

    Is there a more elegant way to act on the first and last items when iterating through a foreach loop than incrementing a separate counter and checking it each time? For instance, the following code outputs: >>> [line1], [line2], [line3], [li

  • JavaScript Variable inside string without concatenation - like PHP 2010-07-21

    I know in PHP we can do something like this : $hello = "foo"; $my_string = "I pity the $hello"; output : "I pity the foo" I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation

  • Elegant Solution to Parsing XElements in a Namespace 2010-08-16

    In a project I am working on, I just finished writing an XSD for my XML so other engineers could work on the XML easier. Along with this XSD came XML namespaces. In my current parsing code, I have been using something like this: XElement element = xm

  • Concatenated / Calculated Columns in Dynamics CRM View 2010-09-08

    I am new to MS Dynamics and I would like to know if there is a way of adding column to a view within that is a concatenation of some other columns, for example: Firstname + ' ' + Lastname As Fullname There doesn't seem like there is an obvious (elega

  • Elegant way to implement a criteria-based search page in Hibernate 2010-10-08

    Using Hibernate how would you design and implement a search criteria page (which has multiple editable/selectable fields/drop-downs as search criteria) such that queries shouldn't clutter data accessor code. I mean no query-string concatenation based

  • Elegant Ruby one liners 2010-11-28

    One of the reasons I like writing in Ruby so much is because it is very capable of achieving a lot via one liners. I like: @sentence = @sentence.split(' ').map!{|x| x = x[0..0].upcase << x[1..-1] }.join(' ') It capitalizes the first letter of e

  • How should I refactor this Haskell code to make it more elegant? 2011-04-01

    As an exercise I wrote a short Haskell function that returns the first four characters of a string, concatenated. I had great trouble converting the chars to strings and resorted to an ugly replicate hack. What's the best way to improve this function

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.168 (s). 11 q(s)