Romain
Romain

Reputation: 659

Find a String in a huge text file

I am developing an internal App that will search things in one text file (~60,000 lines). The user will type a String in the UISearchBar on his iPhone and the App will return the line(s) where the String is located.

This is how I do it.

First I split my text file into an array called entriesInLine:

    var entriesInLine: [String] = []

    let fileWithEntries = NSBundle.mainBundle().pathForResource("database", ofType: "txt")
    var entriesFromFile = String(contentsOfFile: fileWithEntries!, encoding: NSUTF8StringEncoding, error: nil)

    if let content = entriesFromFile {
        self.entriesInLine = content.componentsSeparatedByString("\n")
        println(self.entriesInLine.count)
    }

Then I want the user to be able to search the database using the UISearchBar. Here is my Search method:

 func filterEntries(searchText: String) {
    for var i = 0; i < self.entriesInLine.count; i++  {
        if ( self.entriesInLine[i].rangeOfString(searchText) != nil) {
            self.filteredEntries.append(extractEntry(entriesInLine[i]))                            

        }

And here is my searchDisplayController method:

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterEntries(searchString)

}

Everything is kind of working but it's too slow because arrays are huge.

Do you know a faster way of searching the content in my text file?

I will really appreciate your help for that!

Thank you

Upvotes: 1

Views: 1926

Answers (1)

johny kumar
johny kumar

Reputation: 1270

Try this I have Tested.

 var bundle: NSString = NSBundle.mainBundle().pathForResource("File", ofType: "")!
 var entriesFromFile: NSString = NSString.stringWithContentsOfFile(bundle, encoding: NSUTF8StringEncoding, error: &attributeError) as NSString
 var range: NSRange = entriesFromFile.rangeOfString("rrr")
 var substring: NSString = entriesFromFile.substringToIndex(range.location)
 var arr: NSArray = substring.componentsSeparatedByString("\n")

 print("Occurence of String in File on Line Number", arr.count)

Upvotes: 3

Related Questions