//

//  DIAStringExtension.swift

//  General purpose... YMMV

//

//  Created by coti on April 5 2017 (Ermingen)

//  Copyright © 2017 coti. All rights reserved.

//


import Foundation


extension String {

  //

  // This method splits the string into fields according to the lenghts passed to it

  // Some validation is made, the number of characters and the sum of widths must

  // coincide.according

  //

  // Info is shown id DEBUG is defined in Other Swift Flags

  //

  func splitColumns(_ w:[Int]) -> [String] {

    let calculatedWidth = w.reduce(0, { $0 + $1 } )

    let realWidth = self.characters.count

    

    #if DEBUG

      print("calculatedWidth is \(calculatedWidth)")

      print("realWidth is \(realWidth)")

    #endif

    if calculatedWidth != realWidth {

      print("Length of string is not correct")

      return [String]()

    }

    

    var tokens = [String]()

    // Define, a, b, range and token

    // Their values will be set in the loop

    //

    var a = self.startIndex

    var b = a

    var range = a..<b

    var token = ""

    // token and range could be eliminated

    for i in 0..<w.count {

      a = i == 0 ? self.startIndex : b 

      b = self.index(a, offsetBy: w[i])

      range = a..<b

      token = self.substring(with:range).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

      #if DEBUG

        print("\(token)")

      #endif

      tokens.append(token)

    }

    return tokens

    

  } // End of splitColumns(_:)

  

  //

  // This method mimics Java's split method

  // Some validation is made, if no delimiter is found then

  // the method returns an empty list of String

  //

  func split(with delimiter:String) -> [String] {

    if !self.contains(delimiter) {

      return [String]()

    }

    return self.components(separatedBy:delimiter)

  }

  

  

} //End of extension String