Harsha
Harsha

Reputation: 239

how to remove a second AMPERSAND in a string?

1.how to remove second AMPERSAND from following string? "apple&banana&grape&apple"

2.how to split the string at second AMPERSAND for following string? I want to ignore the first AMPERSAND and split from second AMPERSAND onwards. "apple&banana&grape&apple"

Upvotes: 1

Views: 303

Answers (3)

Pramod
Pramod

Reputation: 1416

arr = "apple&banana&grape&apple".split('&')
#arr = ["apple", "banana", "grape", "apple"]

To solve first query,

arr[0..1].join('&').concat(arr[2..-1].join('&'))
# "apple&bananagrape&apple" 

For second query,

[words[0..1].join('&'), words[2..-1]].flatten
#["apple&banana", "grape", "apple"] 

Upvotes: 1

SRack
SRack

Reputation: 12203

If you split the string by the &, it's quite simple to rejoin the first two / last two and convert back into a string or array:

words = "apple&banana&grape&apple".split('&')

# First query
words[0..1].join('&') + words[2..-1].join('&')
# Giving you: "apple&bananagrape&apple"

# Second query
[words[0..1].join('&'), words[2..-1].join('&')]
# Giving you: ["apple&banana", "grape&apple"]

You could tweak this for different length strings and separators as needed.

I imagine there's a good solution using regex matchers, but I'm not too hot on them, so hope this helps in some way!

Upvotes: 0

AbM
AbM

Reputation: 7779

You can use gsub with a block:

For your first case:

 index_to_remove = 2 
 current_index = 0
 my_string = "apple&banana&grape&apple"
 my_string.gsub('&') { |x| current_index += 1; current_index == index_to_remove ? '' : x} 
#=> "apple&bananagrape&apple"

For your second case, you can replace the second & with a unique value and split on that:

index_to_split = 2 
current_index = 0
my_string = "apple&banana&grape&apple"
my_string.gsub!('&') { |x| current_index += 1; current_index == index_to_split ? '&&' : x}
my_string.split('&&')
#=> ["apple&banana", "grape&apple"]

Upvotes: 0

Related Questions