"a b c" would become "a b c"
. For both of these, we're going to monkey patch the string class. Here's the code ...
class String
def remove_consecutive_spaces
self.gsub(/ +/, " ")
end
end
All we do is do a global substitution of one or more spaces with a single space. This would be quite a bit trickier in C say which is why it ends up in interview questions.
The second (or first) problem is to remove duplicate characters from a string. For example, "aaaabbbb"
becomes "ab"
and "abcbd"
becomes "abcd"
. This one is a bit trickier but shows another good example of how useful inject()
can be. Here's the code ...
class String
def remove_duplicate_characters
self.split(//).inject([]) { |a, c| a << c if !a.include?(c); a }.join
end
end
Going through it from left to right, we have first the split(//)
which will turn the array into a string of characters. With that string of characters we do an inject([])
which a) initializes a new empty array (sometimes called the "memo") and then runs through the character array adding a character "c" to the array "a" if it's not already there include?
. The ; a
returns the current array back to the inject
. Finally, we recreate the string by doing a join
on the character string array.
Let me know if you have questions or comments.
Saturday, September 3, 2011
Two String Exercise via Programming Praxis
Here's another one (or two rather) from Programming Praxis. Let's take a look at the second one first as it's trivial in ruby. If we're given a string, how do we replace multiple spaces with single spaces. F/or example the string
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment