Strings in swift
Tags: swift, beginners, programming
Published: 2021-12-26 16:27:21

### String literals
A sequence of characters surrounded by double quotes(")

```swift
let message:String = "Good morning"
```

### 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 (""")

```swift
let multilineMessage:String = """Hello user!
                       hope you are doing good"""
```
### Extended string delimiters (#)
We can place a string literals within extended delimiters to include special characters in a string without invoking their effect.

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

//prints hello \(name)
```

### Initialising and Empty string

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

if str.isEmpty { //returns a boolean value
print("The string is empty")
}
```
refer - [Difference between these both declaration](https://stackoverflow.com/questions/31197008/swift-string-via-string-literal-vs-initializer)

### Concating strings and character and String length

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

print(welcome.count) //10
```
### 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.

```swift
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
```

**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.

```swift
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!"
```

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:

```swift
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"
```
**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhvki2kx11sri3dp0gjx.png)

```swift
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)
```

### 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.