Comparing Strings with variable white spacing

Stings may sound like 101 of programming, but just a glimpse of TAOCP would turn the thought inside out!

Comparing Strings is on of the most common tasks that any programmer would do, but the fun never ends with strings!

Comparing Strings with variable white spacing, is also one among the most common cases, below /me has tried to collect the most intuitive way of doing it in Ruby, Perl, Python and Javascript

Say we have two strings str1="hemanth is testing" and str2="hemanth is testing" with white spaces in consideration, these two strings are not equal, but logically handling the extra spaces would reveal that these strings are equal, which plays a very important role in fileds like : parsing, NPL, testing and so forth.

On the other hand, if we try to compare strings ignoring cases, we will end up with wrong results, say for example comparing two strings like "a book" and "ab o ok" ignoring spaces would be the same, but they are in real not!

The below are the ways to compare strings with variable strings are as below :

Ruby : Out of all the languages considered here, /me selected ruby because, none of the other languages provide such an easy way to do this with their own standard libs.

>> "a book".squeeze == "a       book".squeeze
=> true

Perl : Perl's R.E are always interesting.

$str1 = "hemanth is     testing" ;

$str2 = "hemanth is testing" ;

$str1 =~ tr / //s;

$str1 == $str2 ? print 1 : print 0;


Python: Indeed the famous "import re"

>>> s1="hemanth is testing"
>>> s2="hemanth is    testing"
>>> re.sub("[\x00-\x20]+", " ",s2) == s1



str1 = "hemanth is testing"
str2 = "hemanth is      testing"
str1.replace(/\s+/g, " ") == str2.replace(/\s+/g, " ")

Do let me know your ways of doing the same!

_Update 0:_

As per the comments below from Kevin, it worth to keep this is mind :

1.9.3-p327 :001 > "a book".squeeze == "a bok".squeeze
 => true 
1.9.3-p327 :002 > "a book".squeeze(" ") == "a book".squeeze(" ")
 => true 
1.9.3-p327 :003 > "a book".squeeze(" ") == "a bok".squeeze(" ")
 => false 

P.S : We are passing an empty sting to squeeze!

Share this