Search for substrings

I want to search for substrings.

eg.
in string: "aaaaBaaaCaa",
there're 3: "aaa",
start pos: 0, 1, 5

The following is what I do in C++. How can I do it in Swift?

Thanks

#include <iostream>
#include <string>
using namespace std;

int main(int argc, const char * argv[]) {
    string s1 = "aaaaBaaaCaa";
    string s2 = "aaa";
    
    for (string::size_type n = 0; n != s1.size(); n++) {
        n = s1.find(s2, n);
        if (n != string::npos) {
            cout << n << ": " << s1.substr(n) << endl;
        } else {
            break;
        }
    }
    
    return 0;
}

/*
0: aaaaBaaaCaa
1: aaaBaaaCaa
5: aaaCaa
*/

You may find the section “accessing string elements” useful from this page:

https://developer.apple.com/documentation/swift/string

Also String conforms to the Collection protocol, so this page may also be useful:

https://developer.apple.com/documentation/swift/collection

I got the following code.

Are String.Index and Bound (eg, Range.lowerBound) exchangable in string subscript?

index = s1.index(after: range.lowerBound)

Thanks

import Foundation

let s1 = "aaaaBaaaCaa"
let s2 = "aaa"
var index = s1.startIndex

while index != s1.endIndex {
    if let range = s1[index...].range(of: s2) {
        index = s1.index(after: range.lowerBound)
        let pos = s1.distance(from: s1.startIndex, to: range.lowerBound)
        print(pos, ":", s1[range.lowerBound...])
    } else {
        break
    }
}

/*
 0 : aaaaBaaaCaa
 1 : aaaBaaaCaa
 5 : aaaCaa
 */

They are the same type, so yes.

1 Like
Terms of Service

Privacy Policy

Cookie Policy