DEV Community

Cover image for Strings
Krishna  Damaraju
Krishna Damaraju

Posted on

Strings

Strings

1️⃣ Declaration

Javascript

// Both Single and Double quotes are OK to create strings in JS
var string1 = "Hello Js!!" 
var string2 = 'Hello Js!!' 

Enter fullscreen mode Exit fullscreen mode

Swift

// Only Double quotes are OK to create strings in JS
var string1 = "Hello Js!!" 
var string2 = 'Hello Js!!'  
Enter fullscreen mode Exit fullscreen mode

2️⃣ Length

Javascript


"Hello world!!".length // 13 (counts empty spaces too)

Enter fullscreen mode Exit fullscreen mode

Swift

"Hello world!!".count // 13 (counts empty spaces too)
Enter fullscreen mode Exit fullscreen mode

3️⃣ Case Transformation

Javascript


"Hello world!!".toLowerCase() // hello world!!
"Hello world!!".toUpperCase() // HELLO WORLD!! 

Enter fullscreen mode Exit fullscreen mode

Swift

"Hello world!!".lowercased() // hello world!!
"Hello world!!".uppercased() // HELLO WORLD!! 
Enter fullscreen mode Exit fullscreen mode

4️⃣ Template literals

Javascript

const name = "Krishna"

const message = `Hello there, i am ${name}.`
Enter fullscreen mode Exit fullscreen mode

Swift

let name = "Krishna"

let message = "Hello there, i am \(name)."
Enter fullscreen mode Exit fullscreen mode

5️⃣ Split

Javascript

var string = "Hello world!!"

string.split("")
Enter fullscreen mode Exit fullscreen mode

Swift

var string = "Hello world!!"

string.split(separator: "")
Enter fullscreen mode Exit fullscreen mode

6️⃣ Multi-line strings

Javascript

// most used way
var string = `
A long time ago 
in a galaxy far far away
javascript is being used for coding`

Enter fullscreen mode Exit fullscreen mode

Swift

// """ are always to be alone
var string = """
A long time ago 
in a galaxy far far away
Swift is being used for coding
"""
Enter fullscreen mode Exit fullscreen mode

7️⃣ Concatination

Javascript


var string = "Hello"
var string2 = 'world'

var string3 = string + string2 // string.concat(string2)
Enter fullscreen mode Exit fullscreen mode

Swift

var string = "Hello"
var string2 = 'world'

var string3 = string + string2
Enter fullscreen mode Exit fullscreen mode

8️⃣ Typecasting

Javascript


var someNumber = 12345

var asString = String(someNumber) // -OR- someNumber.toString() -OR- `${someNumber}`
Enter fullscreen mode Exit fullscreen mode

Swift

var someNumber = 12345

var asString = String(someNumber) // -OR- '\(someNumber)'
Enter fullscreen mode Exit fullscreen mode

More examples are added on the go

Top comments (0)