Quantcast
Channel: Ruby – My Programming Blog
Viewing all articles
Browse latest Browse all 12

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

$
0
0

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


Tagged: algorithm, reverse, reverse sentence, reverse string, reverse word, Ruby

Viewing all articles
Browse latest Browse all 12

Trending Articles