How to find all positions of one string in another string in swift2 ?

后端 未结 4 1358
执念已碎
执念已碎 2021-01-02 06:12

I can find first position of string \"ATG\" in myString \"ATGGACGTGAGCTGATCGATGGCTGAAATGAAAA\" (i.e. index range is 0..<3) by using code below. Question is how to find al

4条回答
  •  执笔经年
    2021-01-02 06:48

    Welcome to SO.

    This would be a good programming exercise. I suggest that you take it on as a learning project.

    Write a function that takes a string to search in, and a string to search for, and returns an optional array of NSRange objects. If it doesn't find any occurrences, the optional would be nil. Alternately, you could always return an array, but have it contain 0 NSRange objects if the string isn't found.

    Have your function use the NSString method rangeOfString:options:range: to search the string. First you would search the entire source string. Once you found the first occurrence, you'd adjust the range parameter to only search the remainder of the source string after that occurrence.

    EDIT:

    An elegant way to do this would be as an extension to the String class. That way you could use your new method as if it was a built-in feature of Strings.

提交回复
热议问题