diff --git a/string_manipulation.rb b/string_manipulation.rb index c8b52e1..c5d27ab 100644 --- a/string_manipulation.rb +++ b/string_manipulation.rb @@ -1,23 +1,93 @@ # A method to reverse a string in place. def string_reverse(my_string) - puts "NOT IMPLEMENTED" + j = my_string.length - 1 + i = 0 + while i < j + temp = my_string[i] + my_string[i] = my_string[j] + my_string[j] = temp + i += 1 + j -= 1 + end + return my_string end # A method to reverse each word in a sentence, in place. def reverse_words(my_words) - puts "NOT IMPLEMENTED" + length = my_words.length + first_i = 0 + + length.times do |i| + if my_words[i] == ' ' || i == length - 1 + last_i = i - 1 + if last_i + 1 == length - 1 + last_i = i + end + while first_i < last_i + temp = my_words[first_i] + my_words[first_i] = my_words[last_i] + my_words[last_i] = temp + first_i += 1 + last_i -= 1 + end + first_i = i + 1 + end + end + return my_words end # A method to reverse the words in a sentence, in place. def reverse_sentence(my_sentence) - puts "NOT IMPLEMENTED" + length = my_sentence.length + + j = my_sentence.length - 1 + i = 0 + while i < j + temp = my_sentence[i] + my_sentence[i] = my_sentence[j] + my_sentence[j] = temp + i += 1 + j -= 1 + end + + first_i = 0 + length.times do |index| + if my_sentence[index] == ' ' || index == length - 1 + last_i = index - 1 + if last_i + 1 == length - 1 + last_i = index + end + while first_i < last_i + temp = my_sentence[first_i] + my_sentence[first_i] = my_sentence[last_i] + my_sentence[last_i] = temp + first_i += 1 + last_i -= 1 + end + first_i = index + 1 + end + end + return my_sentence end # A method to check if the input string is a palindrome. # Return true if the string is a palindrome. Return false otherwise. def palindrome_check(my_phrase) - puts "NOT IMPLEMENTED" - return true + length = my_phrase.length + + if length == 0 + return false + end + + i = 0 + j = -1 + while i < -j + if my_phrase[i] != my_phrase[j] + return false + else + return true + end + end end # A method that updates the string by replacing consecutive repeating characters @@ -44,6 +114,7 @@ def encode_repeating(my_string) puts "Original: #{my_words}" reversed_words = "I nac eb na reenigne" reverse_words(my_words) + if my_words == reversed_words puts "Words reversed correctly. Reversed words: #{reversed_words}" else