-2

how can i remove character from string with rang. for example «banana» i want to remove only a from index (1..<3), i don’t want to remove the first and last character if they where «a»

i want from banana to bnna only removed the two midle.

the only thing i can do now is to remove the all “a”.

var charr = "a"    
var somfruit = "banana"    
var newString = ""

for i in somfruit{
    if charr.contains(i) {
        continue
    }
   newString.append(i)   
}

print(newString)
Ted
  • 3,985
  • 1
  • 20
  • 33
slowTurtle
  • 17
  • 6

1 Answers1

0

In SWIFT 5 try:

var charr = "a"    
var somfruit = "banana"    
var newString = ""

let lower = somfruit.firstIndex(of: charr) + 1
let upper = somfruit.lastIndex(of: charr) - 1
newString = somfruit.replacingOccurrences(of: charr, with: '', option: nil, range: Range(lower, upper)

print(newString)

This is simplified. firstIndex and lastIndex returns Int? so you have to check they exist and they are not equals.

Alrik
  • 100
  • 6