Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Longest String Matching

by grizzley (Chaplain)
on Apr 08, 2013 at 14:19 UTC ( [id://1027515]=note: print w/replies, xml ) Need Help??


in reply to Longest String Matching

As you know exactly where you want to match (at the end of string), you can first get length n of a word you are searching for, then using substr function get substring of length n of the word you are searching in and just do eq comparison of two strings:
#!perl -l @array = ('own', 'known', 'owl'); $q = 'unknown'; $longestmatching = ''; $longestn = 0; for $testword(@array) { $n = length($testword); next if $n <= $longestn; $substr = substr($q, length($q)-$n, $n); if($testword eq $substr) { $longestmatching = $testword; $longestn = $n; } } print $longestmatching;
Additionally you can do sort of @array from longest to shortest string as others mentioned.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1027515]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-24 18:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found