Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 String with substringWithRange

Tags:

string

ios

swift2

I am trying to get first char from String. It should be easy but I can't do in Swift 2.0 (with Xcode beta 6).

Get nth character of a string in Swift programming language

I have tried that method also. It use extension but I can't retrieve using that method. May I know how to do?

like image 707
Khant Thu Linn Avatar asked Sep 05 '15 12:09

Khant Thu Linn


3 Answers

Two solutions without casting to NSString

let string = "Hello"
let firstChar1 = string.substringToIndex(string.startIndex.successor())

let firstChar2 = string.characters.first

Update for Swift 2:

Since Swift 2 returns Character rather than String a new String must be created.

let firstChar2 = String(string.characters.first!)

Update for Swift 3:

successor() has been replaced with index(after:..)

let firstChar1 = string.substring(to:string.index(after: string.startIndex))
like image 193
vadian Avatar answered Nov 18 '22 06:11

vadian


Try this,

let str = "hogehoge"
let text = (str as NSString).substringFromIndex(1) // "ogehoge"
like image 27
pixyzehn Avatar answered Nov 18 '22 08:11

pixyzehn


For what it's worth (and for people searching for and finding this topic), without casting the String to NSString, you need to do the following with Swift 2.1:

let myString = "Example String"
let mySubString = myString.substringWithRange(Range<String.Index>(start: myString.startIndex.advanceBy(0), end: myString.startIndex.advanceBy(4)))

print(mySubString) //'Exam'

This would printout "Exam". Must say that it's much more verbose than in Obj-C. And that's saying something... ;-) But it gets the job done and without casting to NSString.

like image 4
Harmen ter Horst Avatar answered Nov 18 '22 07:11

Harmen ter Horst