Tokenize a string: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 6: Line 6:
'''Interpreter:''' [[Perl]] any 5.X
'''Interpreter:''' [[Perl]] any 5.X


As a one liner without a trailing period, and most efficient way of doing it as you don't have to define an array.
# in split, between the // goes a regex
my @words = split(/,/, "Hello,How,Are,You,Today");
print join('.', @words); # does not include a trailing period


print join('.', split(/,/, "Hello,How,Are,You,Today"));
Alternate

If you needed to keep an array for later use, again no trailing period


my @words = split(/,/, "Hello,How,Are,You,Today");
my @words = split(/,/, "Hello,How,Are,You,Today");
print $_.'.' for (@words); # includes a trailing period
print join('.', @words);


If you really want a trailing period, here is an example
Or my personal favorite, the one liner


print join('.', split(/,/, "Hello,How,Are,You,Today"));
my @words = split(/,/, "Hello,How,Are,You,Today");
print $_.'.' for (@words); # includes a trailing period


==[[Ruby]]==
==[[Ruby]]==

Revision as of 16:52, 2 February 2007

Task
Tokenize a string
You are encouraged to solve this task according to the task description, using any language you may know.

Separate the string "Hello,How,Are,You,Today" by commas into an array so that each index of the array stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period.

Perl

Interpreter: Perl any 5.X

As a one liner without a trailing period, and most efficient way of doing it as you don't have to define an array.

print join('.', split(/,/, "Hello,How,Are,You,Today"));

If you needed to keep an array for later use, again no trailing period

my @words = split(/,/, "Hello,How,Are,You,Today");
print join('.', @words);

If you really want a trailing period, here is an example

my @words = split(/,/, "Hello,How,Are,You,Today");
print $_.'.' for (@words); # includes a trailing period

Ruby

    string = "Hello,How,Are,You,Today".split(',')
    string.each do |w|
         print "#{w}."
    end