Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Saturday, April 21, 2007

Java/Perl - split

split breaks up (or splits) a string into "tokens" or substrings according to a separator. split uses a regular expression as the separator.

Perl


#!/usr/bin/perl
use strict;
use warnings;

my @fields = split /:/, "jim:bob:frank:steve";
foreach my $field (@fields) {
print "$field\n";
}

my $string = "one two three four\tfive";
my @array = split /\s+/, $string;
foreach my $el(@array) {
print "$el\n";
}


Output:

jim
bob
frank
steve
one
two
three
four
five


Java 1.4 added the split() method to the String class.

Java


public class Split
{
public static void main(String[] args)
{
String string1 = "jim:bob:frank:steve";
String[] names = string1.split(":");
for(int i=0; i<names.length; i++)
System.out.println(names[i]);

String string2 = "one two three four\tfive";
String[] words = string2.split("\\s+");
for(int i=0; i<words.length; i++)
System.out.println(words[i]);
}
}


It is also possible to use the java.util.StringTokenizer to break a string into tokens.


import java.util.StringTokenizer;

public class StringToke
{
public static void main(String[] args)
{
String string1 = "jim:bob:frank:steve";
StringTokenizer st1 = new StringTokenizer(string1,":");
while(st1.hasMoreTokens())
System.out.println(st1.nextToken());

String string2 = "one two three four\tfive";
StringTokenizer st2 = new StringTokenizer(string2);
while(st2.hasMoreTokens())
System.out.println(st2.nextToken());
}
}


Output:

jim
bob
frank
steve
one
two
three
four
five


If no regular expression pattern is used, split defaults to using white space as the separator. (both in Perl and Java)

No comments:

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels