-2

I am trying to count the number of different Strings in an array. For example, my array is:

let stringArray = ["test", "test", "test1", "test2"]

The output should be "3" because "test" and "test" are the same, but "test", "test1", and "test2" are different. I am thinking about using a nested for loop to check the stringArray string in the first loop against all of the other elements in stringArray, but I can't quite get it to work. The only thing I can think of right now is to check on the inner loop if the strings are equal and break out -> go onto the next element. The problem I have is checking if the inner loop is on the last element. Here is what I have come up with:

var differentStrings = Int()
let stringArray = ["test", "test", "test1", "test2"]
    for str in stringArray {
        for str2 in stringArray {
            if (str == str2) {
                break
            } else {
                differentStrings = differentStrings + 1
            }
        }
    }
    print(differentStrings)

The output here is incorrect -> it prints out 5 because I am not checking in the else statement if str2 is the last element in the inner loop.

How do I get the number of different strings in an array?

8
  • 1
    stackoverflow.com/questions/27624331/… Commented Dec 29, 2016 at 19:02
  • 1
    It's a one-liner: let ct = Set(stringArray).count Commented Dec 29, 2016 at 19:07
  • 3
    @matt Don't even need an NSCountedSet. A native Swift set is preferable Commented Dec 29, 2016 at 19:09
  • @Alexander And you caught me in time that I could still edit it! Thx Commented Dec 29, 2016 at 19:10
  • 2
    This question is closed @DanLevy. And rightly so. Next time, search first. Please. Commented Dec 29, 2016 at 19:19

2 Answers 2

2

If ordering doesn't matter, just make a Set:

let differentStrings = Set(stringArray)

or if you're just using a literal:

let differentStrings: Set = ["test", "test", "test1", "test2"]

Then just get the count of it:

let numDifferentStrings = differentStrings.count

Sounds to me like someone didn't read the Swift language guide ;)

Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you make a second array and put only new strings into it? So you iterate through your array. If the value is not in array2, put in array 2. Once you get through the entire first array, you can just get the length of the second array and have your answer.

1 Comment

Because quadratic time complexity makes kitties cry

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.