Dew Time
Dew Time

Reputation: 878

Check for duplicate characters in string using for-in loops in Swift

I did this using while loops but I'm wondering if there's a way to do this with for loops. I'm trying to write this clean so I can write it on a whiteboard for people to understand.

var str = "Have a nice day"

func unique(_ str: String) -> String {
    var firstIndex = str.startIndex

    while (firstIndex != str.endIndex) {
        var secondIndex = str.index(after: firstIndex)

        while (secondIndex != str.endIndex) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
            secondIndex = str.index(after: secondIndex)
        }
        firstIndex = str.index(after: firstIndex)
    }
    return "All the characters are unique"
}

print("\(unique(str))")

Upvotes: 6

Views: 8855

Answers (9)

Andy Jazz
Andy Jazz

Reputation: 58113

Isograms

The isograms are words/phrases in which no one letter is repeated, i.e. all letters are unique. The following algorithm compares lowercased characters ignoring whitespaces between words.

Here's my code:

func isThisIsogram(_ string: String) -> Bool {
    var str = string.lowercased()
    str.replace(" ", with: "")
    let characters = Set<Character>(str)
    
    for char in characters {
        switch str.filter({ $0 == char }).count {
            case 2... : return false
            default   : continue
        }
    }
    return true
}

isThisIsogram("private logs")                // true
isThisIsogram("tomorrow morning")            // false
isThisIsogram("🤓 🥶 🥵 😶‍🌫️")                 // true
isThisIsogram("γράμματα")                    // false
isThisIsogram("我 你 她")                     // true

Upvotes: 0

mathisankar
mathisankar

Reputation: 1

let inputStr = "sakkett"
var tempStr = String()

for char in inputStr
{
    if tempStr.contains(char) == false
    {
        tempStr = tempStr.appending(String(char))

        let filterArr = inputStr.filter({ $0 == char})
        if filterArr.count > 1 {
            print("Duplicate char is \(char)")
        }
    }
}

//Output:
Duplicate char is k
Duplicate char is t

Upvotes: 0

Hitesh Sapra
Hitesh Sapra

Reputation: 1

let input = "ssaajaaan"
var count = 1
for i in 0..<input.count
{
   let first = input[input.index(input.startIndex, offsetBy: i)]
    if i + 1 < input.count
    {
let next = input[input.index(input.startIndex, offsetBy: i + 1)]
        if first == next
        {
            count += 1
        }
        else
        {
            count = 1
        }
    }
    if count >= 2
    {
        print(first," = ",count)
    }

}

Upvotes: 0

yasin89
yasin89

Reputation: 173

let str = "Hello I m sowftware developer"
var dict : [Character : Int] = [:]

let newstr = str.replacingOccurrences(of: " ", with: "")
print(newstr.utf16.count)

for i in newstr {
    if dict[i] == nil {
        dict[i] = 1
    }else{
        dict[i]! += 1
    }
}

print(dict) // ["e": 5, "v": 1, "d": 1, "H": 1, "f": 1, "w": 2, "s": 1, "I": 1, "m": 1, "o": 3, "l": 3, "a": 1, "r": 2, "p": 1, "t": 1]

You can find any value of char how many times write in string object.

Upvotes: 2

cmaroney
cmaroney

Reputation: 283

this is my solution

func hasDups(_ input: String) -> Bool {
    for c in input {
        if (input.firstIndex(of: c) != input.lastIndex(of: c)) {
            return true
        }
    }
    return false
}

Upvotes: 0

garafajon
garafajon

Reputation: 1458

I used a hash to do it. Not sure how fast it is but it doesn't need to be in my case. (In my case I'm doing phone numbers so I get rid of the dashes first)

            let theLetters = t.components(separatedBy: "-")
            let justChars = theLetters.joined()
            var charsHash = [Character:Int]()
            justChars.forEach { charsHash[$0] = 1 }
            if charsHash.count < 2 { return false }

... or more compact, as an extension...

extension String {
    var isMonotonous: Bool {
        var hash = [Character:Int]()
        self.forEach { hash[$0] = 1 }
        return hash.count < 2
    }
}

let a = "asdfasf".isMonotonous   // false
let b = "aaaaaaa".isMonotonous   // true

Upvotes: 3

bubuxu
bubuxu

Reputation: 2197

As @adev said, there are many ways to finish this. For example, you can use only one for-loop with a dictionary to check the string is unique or not:

Time complexity: O(n). Required O(n) additional storage space for the dictionary.

func unique(_ input: String) -> Bool {

    var dict: [Character: Int] = [:]

    for (index, char) in input.enumerated() {
        if dict[char] != nil { return false }
        dict[char] = index
    }

    return true

}

unique("Have a nice day") // Return false
unique("Have A_nicE-dⒶy") // Return true

Upvotes: 2

Guy Kogus
Guy Kogus

Reputation: 7341

You can use the indices of the characters:

var str = "Have a nice day"

func unique(_ str: String) -> String {
    for firstIndex in str.characters.indices {
        for secondIndex in str.characters.indices.suffix(from: str.index(after: firstIndex)) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

print("\(unique(str))")

Upvotes: 4

adev
adev

Reputation: 2092

Here is the for-loop version of your question.

let string = "Have a nice day"

func unique(_ string: String) -> String {
    for i in 0..<string.characters.count {
        for j in (i+1)..<string.characters.count {
            let firstIndex = string.index(string.startIndex, offsetBy: i)
            let secondIndex = string.index(string.startIndex, offsetBy: j)
            if (string[firstIndex] == string[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

There are a lot of ways this can be achieved and this is just one way of doing it.

Upvotes: 2

Related Questions