Working with String in Swift

In this post, I won’t introduce String in Swift. What I write in this post is about manipulating String.

Get a string’s length

var str = "Hello, I'm a string"
count(str) //19

Split a string by a seperator

In this example, I split a string by space character.

var str = "Hello, I'm a string"
str.componentsSeparatedByString(" ") 
// ["Hello,", "I'm", "a", "string"]

Trim

In this example, I remove all leading and trailing whitespace from a string.

var str = "  Hello, I'm a string   "
str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
//"Hello, I'm a string"

Replace

var str = "Hello, I'm a string"
str.stringByReplacingOccurrencesOfString("Hello", withString: "Hi")
//"Hi, I'm a string"

Substring

var str = "Hi, I'm a string"
var range = Range<String.Index>(start: advance(str.startIndex, 4), end: advance(str.endIndex, -7))
str.substringWithRange(range)
//"I'm a"

Prefix and Suffix

var str = "Hi, I'm a string"
str.hasPrefix("Hi") //true
str.hasSuffix("string") //true

Check if a string contains another string

var str = "Hi, I'm a string"
if str.rangeOfString("Hi") != nil
{
    print("Contains!")
}

I hope you find useful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s