DEV Community

Ajithmadhan
Ajithmadhan

Posted on • Updated on

Strings in swift

String literals

A sequence of characters surrounded by double quotes(")

let message:String = "Good morning"
Enter fullscreen mode Exit fullscreen mode

multiline string literals

If we need a string that spans several lines, use multiline string literals - a sequence of characters surrounded by the three double quotes (""")

let multilineMessage:String = """Hello user!
                       hope you are doing good"""
Enter fullscreen mode Exit fullscreen mode

Extended string delimiters (#)

We can place a string literals within extended delimiters to include special characters in a string without invoking their effect.

let name = "Ajith"
print(#"hello \(name)"#)

//prints hello \(name)
Enter fullscreen mode Exit fullscreen mode

Initialising and Empty string

var str = "" //empty string literals
var newStr = String() //initialiser syntax

if str.isEmpty { //returns a boolean value
print("The string is empty")
}
Enter fullscreen mode Exit fullscreen mode

refer - Difference between these both declaration

Concating strings and character and String length

let str = "Hello"
let str2 = "World"
let welcome = str1 + str2
print(welcome) //HelloWorld

print(welcome.count) //10
Enter fullscreen mode Exit fullscreen mode

Accessing and modifying string

Different character can require different amount of memory to store, so in order to determine which character is at a particular position, you might iterate over each unicode scalar from the start or end of that string.
For this reason swift strings cannot indexed by integer value.

  • we can access the indices before and after a given index using the index(before:) and index(after:) methods of strings.To access an index farther away from the given index, we use index(_:offsetBy:) method.
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.index(before: greeting.endIndex)]
// !
greeting[greeting.index(after: greeting.startIndex)]
// u
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a
Enter fullscreen mode Exit fullscreen mode

Use the indices property to access all of the indices of individual characters in a string.

Inserting and removing

To insert a single character into a string at a specified Index, use the insert(_:at:) method, and to insert the contents of another string at a specified index, we use insert(contentsOf:at:) method.

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome now equals "hello!"

welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there!"
Enter fullscreen mode Exit fullscreen mode

To remove a single character from a string at a specified index, use the remove(at:) method, and to remove a substring at a specified range, use the removeSubrange(_:) method:

welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome now equals "hello there"

let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome now equals "hello"
Enter fullscreen mode Exit fullscreen mode

Note:You can use the insert(:at:), insert(contentsOf:at:), remove(at:), and removeSubrange(:) methods on any type that conforms to the RangeReplaceableCollection protocol. This includes String, as shown here, as well as collection types such as Array, Dictionary, and Set.

Substring

When you get a substring from a string—for example, using a method like prefix(_:)—the result is an instance of Substring, not another string.Substrings in Swift have most of the same methods as strings, which means you can work with substrings the same way you work with strings. However, unlike strings, you use substrings for only a short amount of time while performing actions on a string. When you’re ready to store the result for a longer time, you convert the substring to an instance of String.

Substring storage

let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"

// Convert the result to a String for long-term storage.
let newString = String(beginning)
Enter fullscreen mode Exit fullscreen mode

Comparing strings

  • Character equality The strings and character equality is checked with the "equal to" operator (==) and the not equal to (!=) as denoted in comparison operators

Prefix and suffix equality

To check whether a string has a particular prefix or suffix, call the string's hasPrefix(:) and hasSuffix(:) methods which returns a boolean value.

Top comments (0)