Home > Mobile >  How to find last occurrence of a substring in a given string?
How to find last occurrence of a substring in a given string?

Time:12-18

I have a string, which describe some word, I must change ending of it to "sd", if ending == "jk". For an example, I have word: "lazerjk", I need to get from it "lazersd".

I tried to use method .gsub!, but it doesn't work correctly if we have more than one occurrence of substring "jk" in a word.

CodePudding user response:

String#rindex returns the index of the last occurrence of the given substring

String#[]= can take two integers arguments, first is index where start to replace and second - length of replaced string

You can use them this way:

replaced = "foo"
replacing = "booo"

string = "foo bar foo baz"
string[string.rindex(replaced), replaced.size] = replacing

string
# => "foo bar booo baz"

CodePudding user response:

"jughjkjkjk\njk".sub(/jk$\z/, 'sd')
 => "jughjkjkjk\nsd"

without $ is probably sufficient.

CodePudding user response:

It sounds like you're looking to replace a specific suffix only. If so, I would probably suggest using sub along with an anchored regex (to check for the desired characters only at the end of the string):

string_1 = "lazerjk"
string_2 = "lazerjk\njk"
string_3 = "lazerjkr"

string_1.sub(/jk\z/, "sd")  
#=>  "lazersd"

string_2.sub(/jk\z/, "sd")  
#=>  "lazerjk\nsd"

string_3.sub(/jk\z/, "sd")
#=>  "lazerjkr"

Or, you could do without a regex at all by using the reverse! method along with a simple conditional statement to sub! only when the suffix is present:

string = "lazerjk"
old_suffix = "jk"
new_suffix = "sd"
string.reverse!.sub!(old_suffix.reverse, new_suffix.reverse).reverse! if string.end_with? (old_suffix)
string 
#=>  "lazersd"

OR, you could even use a completely different approach. Here's an example using chomp to remove the unwanted suffix and then ljust to pad the desired suffix to the modified string.

string = "lazerjk"
string.chomp("jk").ljust(string.length, "sd")
#=>  "lazersd"

Note that the new suffix only gets added if the length of the string was modified with the initial chomp. Otherwise, the string remains unchanged.

CodePudding user response:

If the goal is to substitute the LAST OCCURRENCE (as opposed to suffix only), then this could be accomplished by using sub along with reverse:

string = "jklazerjkm"
old_substring = "jk"
new_substring = "sd"
string.reverse.sub(old_substring.reverse, new_substring.reverse).reverse
#=>  "jklazersdm"
  • Related