-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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dan Levy
  • 3,931
  • 4
  • 28
  • 48

2 Answers2

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 ;)

Alexander
  • 59,041
  • 12
  • 98
  • 151
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.

A. Dickey
  • 141
  • 1
  • 1
  • 6