Problem converting string to int

I take a line read in from a text file and convert into a string array using the following call:
record_pieces_string = line.componentsSeparatedByString("|")


I then try and convert the first entry into an Int.


Whether I try and use:


String(record_pieces_string[0]

or

(record_pieces_string as NSString).integerValue


I get nil.


but if I do this the correct integer value shows up:


print("the value is \(record_pieces_string[0]"


in the debugger screen the value of record_pieces_string[0] is


"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0 \04\0"


What is going on?


Thanks for any help!

How are you reading the file and what is the text encoding for the file?

I don't know what the text file encoding is. I know that there are lots of "\0" that shouldn't be there.




related question: is there any way, in swift or elsewhere to remove all non-ASCII characters from a text file?




I read the file with this function I got off the net:


func nextLine() -> String? {

precondition(fileHandle != nil, "Attempt to read from closed file")

if atEof {

return nil

}

/

var range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length))

while range.location == NSNotFound {

let tmpData = fileHandle.readDataOfLength(chunkSize)

if tmpData.length == 0 {

/

atEof = true

if buffer.length > 0 {

/

let line = NSString(data: buffer, encoding: encoding)

buffer.length = 0

return line as String?

}

/

return nil

}

buffer.appendData(tmpData)

range = buffer.rangeOfData(delimData, options: [], range: NSMakeRange(0, buffer.length))

}

/

let line = NSString(data: buffer.subdataWithRange(NSMakeRange(0, range.location)),

encoding: encoding)

/

buffer.replaceBytesInRange(NSMakeRange(0, range.location + range.length), withBytes: nil, length: 0)

return line as String?

}

/

func rewind() -> Void {

fileHandle.seekToFileOffset(0)

buffer.length = 0

atEof = false

}

/

func close() -> Void {

fileHandle?.closeFile()

fileHandle = nil

}

}

extension StreamReader : SequenceType {

func generate() -> AnyGenerator<String> {

return anyGenerator {

return self.nextLine()

}

}

}


rhia ia the code that calls Streamreader:


let directory = get_string_directory_for_data_files()

fullpath = String(directory) + "/Accounting/new accnt transactions"

print("the path is \(fullpath)")

da_reader = StreamReader(path: fullpath)!

last_absolute_rec_number = 0

for line in da_reader {


thanks for any help!

Maybe you can do it a simpler way (Swift 2)?


File.txt

123|456
123|456


Code

let file = NSBundle.mainBundle().URLForResource("File", withExtension: "txt")!
let content = try! NSString(contentsOfURL: file, encoding: NSUTF8StringEncoding)
let lines = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
let record_pieces_string = lines[0].componentsSeparatedByString("|")
print(record_pieces_string[0]) // 123
print(record_pieces_string[1]) // 456

is there any way, in swift or elsewhere to remove all non-ASCII characters from a text file?

From a text file? Or from a string? In many cases you can use the latter to solve the former (read the file, strip the strip, write the file), so I’m going to focus on that.

My ‘go to’ tool for stuff like this is NSCharacterSet, and the various APIs that use NSCharacterSet. So a really simple option is this.

let asciiPrintable = NSMutableCharacterSet()
asciiPrintable.addCharactersInRange(NSMakeRange(32, 127 - 32))

let testString = "\u{0}bc\u{1}déf\u{2}"

print(
    testString.componentsSeparatedByCharactersInSet(
        asciiPrintable.invertedSet).joinWithSeparator("")
    )
)
// prints 'bcdf'

Or, if you want the results piecemeal, you can stream through the string with NSScanner.

let scanner = NSScanner(string: testString)
scanner.charactersToBeSkipped = asciiPrintable.invertedSet
while !scanner.atEnd {
    var str: NSString?
    if !scanner.scanCharactersFromSet(asciiPrintable, intoString: &str) {
        break
    }
    print(str!)
}

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Problem converting string to int
 
 
Q