4

I have two strings.

str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"

I want to find the first index at which the two strings differ (i.e. str_a[i] != str_b[i]).

I know I could solve this with something like the following:

def diff_char_index(str_a, str_b)
  arr_a, arr_b = str_a.split(""), str_b.split("")
  return -1 unless valid_string?(str_a) && valid_string?(str_b)
  arr_a.each_index do |i|
    return i unless arr_a[i] == arr_b[i]
  end
end

def valid_string?(str)
  return false unless str.is_a?(String)
  return false unless str.size > 0
  true
end

diff_char_index(str_a, str_b) # => 10

Is there a better way to do this?

4 Answers 4

8

Something like this ought to work:

str_a.each_char.with_index
  .find_index {|char, idx| char != str_b[idx] } || str_a.size

Edit: It works: http://ideone.com/Ttwu1x
Edit 2: My original code returned nil if str_a was shorter than str_b. I've updated it to work correctly (it will return str_a.size, so if e.g. the last index in str_a is 3, it will return 4).

Here's another method that may strike some as slightly simpler:

(0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size

http://ideone.com/275cEU

2
  • 2
    I'd prefer str_a.each_char.with_index, as it doesn't create an intermediate array. Nevertheless, +1.
    – Amadan
    Jul 30, 2015 at 3:32
  • Good catch, @Amadan. I always forget about each_char. Jul 30, 2015 at 3:38
2
i = 0
i += 1 while str_a[i] and str_a[i] == str_b[i]
i
1
str_a = "the_quick_brown_dog"
str_b = "the_quick_red_dog"

(0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? }
  #=> 10

str_a = "the_quick_brown_dog"
str_b = "the_quick_brown_dog"

(0..(1.0)/0).find { |i| (str_a[i] != str_b[i]) || str_a[i].nil? }
  #=> 19
str_a.size
  #=> 19 
2
  • Why not just write Float::INFINITY instead of (1.0)/0? Jul 30, 2015 at 5:18
  • @Jordan, I shouldn't be so flippant. I agree that Float::INFINITY is better. In fact, I originally wrote that, but then decided to change it for the benefit of readers unfamiliar with (1.0)/0. Jul 30, 2015 at 20:16
0

This uses a binary search to find the index where a slice of str_a no longer occurs at the beginning of str_b:

(0..str_a.length).bsearch { |i| str_b.rindex(str_a[0..i]) != 0 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.