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.
=> true
Perl : Perl's R.E are always interesting.
Python: Indeed the famous "import re"
>>> s2="hemanth is testing"
>>> re.sub("[\x00-\x20]+", " ",s2) == s1
True
JavaScript
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!
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs