Manipulating strings with Swift - xcode

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?

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.

Related

How do I extract the prefix of a string till the last instance of a specific character?

for eampaple, the specific character is "_":
let str = "a_b_c_d_1";
how can I extract "a_b_c_d" ?
Found a way to do so, I believe there are more elegant ones.
let str = "a_b_c_d_1";
print(strcat_array(array_shift_right(split(str, "_"), 1),""))

regex with quotation mark

How do I use .js to regex out the quotation marks in the following string?
var wtfx = "<div>ExternalClass=5"</div>44FB";
var wtf = /<div>ExternalClass.*>/;
wtf = wtfx.replace(wtf, "");
alert(wtf);
shows this does not work. If I take the '"' out then it does. How do I 'escape' the quote?
for example I'd like to use reg ex on the above wtf string to yield only the string 44FB.
not getting this.
The following Code will alert "44FB":
var wtfx = "<div>ExternalClass=5\"</div>44FB";
var wtf = /<div>ExternalClass.*>/;
wtf = wtfx.replace(wtf, "");
alert(wtf);
The only change is the Backslash before the Quotationmark in line 1.
However, I'm not 100% sure if that is what you want. Feel free to write a comment if you need another result.

removeRange() function gives empty string in Swift 2

The removeRange: is giving me an empty string in Swift 2 and I don't understand why.
The example in the apple documentation is:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
welcome.removeRange(range)
//I get "" as result rather than "hello" where the exclamation mark is removed
What could be the problem?
You start at the endIndex and then you go back by 6. You are now at the beginning of the word. Then you make a range to the end index and you remove the content of this range: of course there's nothing left. :)
For example, it could be this instead:
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)
Or this:
var welcome = "hello!"
let range = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(range)
There's many possible combinations.
the string in apple documentation is
at the time of remove range
var welcome = "hello there!"
The value of welcome.endIndex is 6 so advancedBy(-6) means it goes to 0. Then the range = 0..<6 that means the the range cover the whole string.
If you want "hello" then change only advancedBy(-1).
var welcome = "hello!"
let range = welcome.endIndex.advancedBy(-1)..<welcome.endIndex
welcome.removeRange(range)

How to avoid optional word from the app?

I removed optional from assistance editor by unwrapping but how to get rid of it in the app and get only the number in answer and not the optional word with it?
Since there are two optionals(text from textfield, String to Integer typecasting) you can use the multiple if let conditions here
if let catText = catAge.text ,let cat = Int(catText) {
let age = cat * 7
catAge.text = "your cat is \(age) years old"
}

Dictionary Optional? Confusion in swift

I know there are a lot of posts on this, but I can't seem to figure out what's going on. The dictionary prints fine. It has a list of words with the number of letters for that word as the value. I want to check if another string is in the list. I read a bunch on optionals, but apparently I'm missing something. I think it has to do with that of course.
let path = NSBundle.mainBundle().pathForResource("wordlist", ofType: "txt")
var content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)?.componentsSeparatedByString("\n")
var myDict = [String : Int]()
let compareWord : String? = "TEST"
if let content = content {
for word in 100 ..< 105
{
myDict[content[word]] = countElements(content[word])
}
}
println("\(myDict)")
var num : Int? = 0
println("Num: \(myDict[compareWord!])")
if let num : Int = myDict[compareWord!] {
println("\(compareWord) is a word with \(num) letters")
}
else
{
println("Wasn't a word")
}
**** Updated with a bit more detail of the code.
Here is what I get when I print a section of the dictionary.
[ABBOTSHIPS
: 11, ABBREVIATED
: 12, ABBOTS
: 7, ABBOTSHIP
: 10, ABBREVIATE
: 11]
If I set the test word to one of them I always get nil when checking for it. It seems to work fine when I manually type things in under the playground.
Ensure that componentsSeparatedByString("\n") doesn't leave any other character, such as \r, at the beginning or end of each extracted strings.

Resources