0

I have a string of 11223.3445566.7788.9900 now I want to create a function where I can remove the duplicate of the specific character in that string and leave only the first in the left.

This is my example code on how for better explanation

let string = "11223.3445566.7788.9900"

let removedDuplicate = removeDuplicate(string: string, char: ".")

print(removedDuplicate) // result 11223.344556677889900

You see, Unlike here I only need to remove the duplicate of the specific character in the string, not all duplicated characters.

2 Answers 2

2

You can find the position of the first occurrence of the specific character and then remove all other occurrences after that position:

func removeDuplicate(string: String, char: Character) -> String {
    if var idx = string.firstIndex(of: char) {
        string.formIndex(after: &idx)
        var s = string
        s.replaceSubrange(idx..., with: s[idx...].filter { $0 != char })
        return s
    } else {
        return string
    }
}

Example:

let string = "11223.3445566.7788.9900"
print(removeDuplicate(string: string, char: "."))
// 11223.344556677889900
10
  • or simply return string[...idx] + string[idx...].filter{$0 != char}
    – Leo Dabus
    Sep 16, 2020 at 7:36
  • @LeoDabus: Yes, that is another option. I just wonder why the substring concatenation returns a String and not a SubString ...
    – Martin R
    Sep 16, 2020 at 7:41
  • 1
    @LeoDabus: Now I see it: string[idx...].filter() returns a String, and there is an overload of + taking a sequence as first argument, a String as second argument, and returning a String
    – Martin R
    Sep 16, 2020 at 7:45
  • 1
    @LeoDabus: Check this github.com/apple/swift/pull/10871: “Per guidance in SE-163 that methods that return new strings shouldn't return substrings, Substring shouldn't just take the default for RangeReplaceableCollection.filter of returning Self”
    – Martin R
    Sep 16, 2020 at 18:17
  • 1
    @LeoDabus: That is what I meant, it was added with the pull request from my above link.
    – Martin R
    Sep 16, 2020 at 18:28
1

You can use components(separatedBy:) and joined() to get that working,

func removeDuplicate(string: String, char: String) -> String {
    let arr = string.components(separatedBy: char)
    var result = arr[0]
    if arr.count > 1 {
        result += char + arr[1]
    }
    if arr.count > 2 {
        result += arr[2...].joined()
    }
    return result
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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