0

I am trying to divide a String in Swift. I have the following string

Program - /path/to/file.doc

I want to get three informations out of this string Program /path/to/file.doc file.doc

I began with the following solution

var str = "Program - /path/to/file.doc"
let indi = str.rangeOfString("-")?.startIndex 
let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi!))
let subString2 = str.substringWithRange(Range<String.Index>(start: indi!, end: str.endIndex))

This gives me the results "Program "and "- /path/to/file.doc"

But how can I get file.doc after the last /?

How Can i increase/decrease and range index to avoid blank spaces?

1
  • Unfortunatelly I don't know Swift to answer your question, but In objective-c, I would first get an array from that string using componentsSeparatedByString:@" - ". Then, element 0 is your name and 1 is the path. Use [[NSURL urlWithString:[array lastObject]] lastPathComponent] to get that filename. Commented Sep 8, 2015 at 23:39

1 Answer 1

2

Yes, sidyll's suggestion is correct, it's a very common practice to get components of Unix path by converting it to NSURL. You may want to write something like this:

var str = "Program - /path/to/file.doc"
if let indi = str.rangeOfString(" - ")?.startIndex {
    let subString = str.substringWithRange(Range<String.Index>(start: str.startIndex, end: indi))
    let subString2 = str.substringWithRange(Range<String.Index>(start: indi, end: str.endIndex))
    let fileName = NSURL(string: subString2).lastPathComponent()
}

I strongly suggest you don't do force unwrap like this. Consider situation if this code will work with string without a particular pattern, for example empty string. Correct, runtime error.

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thanks for sending this code. And indeed important suggestions regarding the format and safety.
Minor simplification (from your original code): You don't need Range<String.Index>(start: x, end: y). All of that is equivalent to x..<y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.