How to reverse a String not using built-in reverse method ? How to reverse every word in a sentence? [Ruby]


Hello again!

I am continuing answering to your questions, this one came from marthab86_.

marthab86_ asks:

“I know Ruby has .reverse! , but can you show me how to actually reverse a word or a sentence without reverse ?”

I am sure that there are many resources that have solution for this problem, but since I am asked, lets have one more example here 🙂

Here is what we are going to do. We are going to algorithmically and via the code answer to the following questions in Ruby:

a. How to reverse a string  ?
b. How to reverse each word in a sentence?
c. How to reverse word order in a sentence?

Ok, let’s start.

a. How to reverse a string ?

Since I didn’t have any instructions about complexity, I will do it  the easiest way.

a. Get a number of characters of the string we want to reverse
b. Loop that loops through each characters of the string from last to first
d. Have a new string that append characters, one at a time from, the old string to the new string

If we put it in a code, it will look like this:
Note: I am using Ruby, but this will be almost the same in any other language


def reverse_whole_string(string)
	raise StandardError.new('Passed string cannot be reversed because it is empty') if string.nil? || string.empty?
	end_loop = string.length
	new_string = ''
	while end_loop >= 0
		end_loop -= 1 # arrays start with 0, so we need to do end_loop -1 first
		new_string += string[end_loop]
	end
	new_string
end

The only addition I have here is that I have raised StandardError if a String is nil or an empty string, otherwise it is exactly the same as an algorithm above.

b. How to reverse each word in a sentence?

This one is a bit more complex, but the idea is the same:
a.  For easier manipulation transform sentence into an array of words by splitting string by space
b. Loop through each word in a sentence
c. Reverse each word in a sentence the same way we reverse the string in the example above
d. Add reversed word to a new array
e. Convert new array of reversed words into String by joining elements by space

Here is the code:

def reverse_each_word_in_a_string(string)
	raise StandardError.new('Passed string cannot be reversed because it is empty') if string.nil? || string.empty?
	words = string.split(" ") #splitting string into an Array of words
	new_sentence = []
	words.each do |word|
		# doing the same thing as reverse_whole_string
		# but with eah word from an array
		end_loop = word.length
		new_string = ''
		while end_loop > 0
			end_loop -= 1
			new_string += word[end_loop] #Reversing every letter of each word
		end
		new_sentence << new_string # appending every word to an new Array
		# or you could just do this: new_sentence << reverse_whole_string(word)
	end
	new_sentence.join(' ') #joining Array into a string delimited by spaces
end

This is it, not so bad right ?

So the last thing is:

c. How to reverse word order in a sentence?

a. Convert sentence into an array of words by splitting string by space
b. Loop through each  word starting from last
c. Add every element of an array in a reverse order to a new array
d. Convert array into string by joining array by space

def reverse_word_order_in_a_sentence(string)
 raise StandardError.new('Passed string cannot be reversed because it is empty') if string.nil? || string.empty?
 words = string.split(" ")
 new_sentence = []
 end_loop = words.length
 while end_loop > 0
  end_loop -= 1
  new_sentence << words[end_loop]
 end
 new_sentence.join(' ')
end

This is it, if you have any questions or concerns please leave them in the comment section.

Source code  is available here .

In the second part we will talk about, why built-in ruby functions  are better, and how to measure runtime of your application.

Stay tuned,

Anatoly

Advertisements

About Anatoly Spektor

My name is Anatoly Spektor (originally Anatolijs Spektors) I am Software and Web Developer. I have worked in Seneca Center for Development of Open Technology on Big Blue Button Add-on - Polling Module, Red Hat and some other places :) I am an author of the book 'Eclipse Debugging How To', Muay Thai fighter and amateur photographer ;)
This entry was posted in Ruby and tagged , , , , , . Bookmark the permalink.

4 Responses to How to reverse a String not using built-in reverse method ? How to reverse every word in a sentence? [Ruby]

  1. Pingback: How to measure your Ruby method performance ? [Ruby, Benchmark] | My Programming Blog

  2. natreffi says:

    in your first example since youre decrementing end_loop after the comparison you’re winding up with an additional final character at -1 where

    new_string += string[-1] #=> winds up with a trailing “g”

    perhaps a more concise way to do this would be to use the downto method:

    def reverse_whole_string(string)
    raise StandardError.new(‘Passed string cant be empty’) if string.nil? || string.empty?
    new_string = ””
    for i in (string.length – 1).downto(0)
    new_string += string[i]
    end
    new_string
    end

  3. Pingback: How to measure your Ruby method performance ? [Ruby, Benchmark] – My Programming Blog

  4. Pingback: How to measure your Ruby method performance ? [Ruby, Benchmark] - My Programming Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s