[tpm] Split a string in half

Liam R E Quin liam at holoweb.net
Sat Mar 14 22:55:44 PDT 2009


On Sat, 2009-03-14 at 23:21 -0400, Madison Kelly wrote:
> Hi all,
> 
>    I need to split a sting in half, and I can assume the the middle 
> character in the string will be a space ' ' character. I cannot predict 
> how many spaces will be in the string though.

Here is a literal implementation:

sub splitstringatmiddlespace($)
{
    my ($input) = @_;

    my $length = length($input);
    my $first = substr($input, 0, $length/2);
    my $rest = substr($input, ($length/2 + 1), $length/2);

    return ($first, $rest);
}

This does not check that the middle character is a space,
nor that there is in fact any input.  It also goes wrong
half the time if the input string has an odd number of characters
(violating the simplistic interpretation of the specification,
but good code should handle that case).

But it is an approach easier to modify to handle such cases,
if needed, than the other two mothds posted so far :)

Liam

-- 
Liam Quin - XML Activity Lead, W3C, http://www.w3.org/People/Quin/
Pictures from old books: http://fromoldbooks.org/
Ankh: irc.sorcery.net irc.gnome.org www.advogato.org



More information about the toronto-pm mailing list