ChapterString
ChapterString
swift
// VipinSwift
import Foundation
class ChapterString {
func useOfInit(){
func useOfInitCharacter(){
//Creates a string containing the given character.
// character take only single value
func useOfInitRepeatingCount(){
// Creates a new string/Character representing the given string repeated the
specified number of times.
let s = String(repeating: "ab", count: 10)
print("repeating String = \(s)")
func useOfEmptyAndCount(){
/*
To check whether a string is empty, use its isEmpty property instead of
comparing the length of one of the views to 0. Unlike with isEmpty, calculating a
view’s count property requires iterating through the elements of the string.
because isEmpty check first element
and count check all element and count it so it is slow
*/
func useOfInitScalar(){
//use of scalar is that break the each value of string like provide the
scalar value
var s = "🇮🇳"
s = "HelloWorld"
print("scalar = \(s)")
let first = String(s.unicodeScalars.first!)
print("first scalar = \(first)")
let last = String(s.unicodeScalars.last!)
print("last scalar = \(last)")
func useOfConvertDataAndViceVersa(){
//String to Data(bytes)
let aStr = "Hello World"
let aStrData = aStr.data(using: .utf8)
print("data from String = \(aStrData)")
// Data(bytes) to String
let bStr = String(data: aStrData!, encoding: .utf8)
print("string from data = \(bStr)")
}
func useOfInitFormat(){
//Leading Zeros
let number: Int = 7
let str1 = String(format: "%03d", number) // 007
let str2 = String(format: "%05d", number) // 00007
print("str1 = \(str1)")
print("str2 = \(str2)")
func useOfWriteAndAppend(){
// Appends the given string to this string.
do {
try str.write(to: filename, atomically: true, encoding:
String.Encoding.utf8)
} catch {
// failed to write file – bad permissions, bad filename, missing
permissions, or more likely it can't be converted to the encoding
}
}
func useOfAppendContentOf(){
// append karna ho
var str = "Hello"
str.append(contentsOf: "world")
print("Append Content of string = \(str)")
func useOfAppendSequence(){
// Adds the elements of a sequence or collection to the end of this
collection.
func useOfStaticPlus(){
//basically use of concatenation
var lhsStr = "LHS"
let rhsStr = "RHS"
let firstString = lhsStr + rhsStr
print("simple + = \(firstString)")
lhsStr += rhsStr
print("simple += = \(lhsStr)")
func useOfInsertAt(){
// Inserts a new character at the specified position.
var str = "ABCD"
str.insert("Y", at: str.index(str.startIndex, offsetBy: 2))
str.insert("Z", at: str.startIndex) // it is not use int value because some
string get unicode value so it count the 1 index like smily etc.
print("Insert in string = \(str)")
func useOfReplaceSubRange(){
// Replaces the specified subrange of elements with the given collection.
var nums = [10, 20, 30, 40, 50]
nums.replaceSubrange(1...3, with: repeatElement(1, count: 5))
print("use with array = \(nums)")
// Replaces the text within the specified bounds with the given characters.
var strHelloWorld = "Hello world"
let range = strHelloWorld.range(of: "w")
strHelloWorld.replaceSubrange(range!, with: "B")
print("use with strings = \(strHelloWorld)")
func useOfRemove(){
// Removes and returns the character at the specified position.
var nonempty = "non-emp-ty"
if let i = nonempty.firstIndex(of: "-") {
nonempty.remove(at: i)
}
print("Remove At = \(nonempty)")
// Replaces this string with the empty string. and both are same
var empty = "ghghg"
empty.removeAll()
print("remove all = \(empty)")
func useOfFilter(){
// Returns a new collection of the same type containing, in order, the
elements of the original collection that satisfy the given predicate.
// filter cannot accept nil values
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { (strObj) -> Bool in
return strObj.count < 5
}
print("use of filter = \(shortNames)")
let helloStr = "Hello world"
let abc = helloStr.filter { (obj) -> Bool in
if obj == "a" || obj == "e" || obj == "i" || obj == "o" || obj == "u"{
return false
}else{
return true
}
}
//*
func useOfDrop(){
// Returns a subsequence by skipping elements while predicate returns true
and returning the remaining elements.
// when comes false then it finish the function
let strHelloWorld = "Hello World Atlas"
let subStr = strHelloWorld.drop { (obj) -> Bool in
// return obj == "l" ? true : false
if obj != "l" {
return false
}else{
return true
}
}
print("drop while with string = \(subStr)")
func useOfLowerAndUpperCase(){
let cafe = "BBQ Café 🍵"
print("lower case = \(cafe.lowercased())")
print("upper case = \(cafe.uppercased())")
func useOfFindingSubstrings(){
// Returns a Boolean value indicating whether the string begins with the
specified prefix.
let cafe = "Café du Monde"
print(cafe.hasPrefix("café")) // case sensitive
print(cafe.hasPrefix("Café"))
// Returns a Boolean value indicating whether the string ends with the
specified suffix.
let plans = "Let's meet at the café"
print(plans.hasSuffix("café")) // case sensitive
print(plans.hasSuffix("Café"))
}
func useOfFindingCharacters(){
// Returns a Boolean value indicating whether the sequence contains the
given element.
let str = "Hello world"
print("string = \(str.contains("r"))")
let stringArray = ["Vivien", "Marlon", "Kim", "Karl"]
print("string array = \(stringArray.contains("Marlon"))")
func useOfAllSatisfy(){
// Returns a Boolean value indicating whether every element of a sequence
satisfies a given predicate.
let namesStr = "helloworld"
let allHaveStr = namesStr.allSatisfy { (chrObj) -> Bool in
return chrObj.isLowercase
}
print("Bool string = \(allHaveStr)")
func useOfFirst(){
// Returns the first element of the sequence that satisfies the given
predicate.
let namesArray = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás", "Owl",
"Oven"]
let firstName = namesArray.first
print("first Name without predicate = \(firstName)")
let firstNamePredicate = namesArray.first { (strObj) -> Bool in
return strObj.first == "O"
}
print("first Name start with O = \(firstNamePredicate)")
}
func useOfFirstIndexOf(){
// Returns the first index where the specified value appears in the
collection.
var students = ["Ben", "Ivy", "Jordell", "Jassey","Maxime", "Maxime"]
if let i = students.firstIndex(of: "Maxime"){
students[i] = "Max"
}
print("Array of student after change = \(students)")
func useOfLast(){
// Returns the last element of the sequence that satisfies the given
predicate.
let namesArray = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás",
"Owl", "Oven"]
let lastName = namesArray.last
print("last Name without predicate = \(lastName)")
let lastNamePredicate = namesArray.last { (strObj) -> Bool in
return strObj.last == "a"
}
print("last Name end with a = \(lastNamePredicate)")
}
func useOfLastIndexOf(){
// Returns the last index where the specified value appears in the
collection.
var students = ["Ben", "Ivy", "Jordell", "Jassey","Maxime", "Maxime"]
if let i = students.lastIndex(of: "Maxime"){
students[i] = "Max"
}
print("Array of student after change = \(students)")
// Returns the index of the last element in the collection that matches
the given predicate.
if let i = students.lastIndex(where: { (strObj) -> Bool in
return strObj.hasPrefix("J")
}){
print("first object string start with J = \(students[i])")
}
func useOfSubscript(){
// Accesses a contiguous subrange of the collection’s elements.
let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2 ..< streets.endIndex]
print("streets array = \(streetsSlice)")
// The range expression is converted to a concrete subrange relative to this
collection. For example, using a PartialRangeFrom range expression with an array
accesses the subrange from the start of the range expression until the end of the
array.
let streetsSlicePartial = streets[2...]
print("streets array with partial range = \(streetsSlicePartial)")
// You can use the same indices for subscripting a string and its substring.
For example, this code finds the first letter after the first space:
let str = "Greetings, friend! How are you?"
let firstSpace = str.firstIndex(of: " ") ?? str.endIndex
let substr = str[firstSpace...]
if let nextCapital = substr.firstIndex(where: { (strObj) -> Bool in
return strObj >= "A" && strObj <= "Z"
}){
print("Capital after a space = \(str[nextCapital])")
}
}
func useOfPrefix(){
// A closure that takes an element of the sequence as its argument and
returns true if the element should be included or false if it should be excluded.
Once the predicate returns false it will not be called again.
let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts", "Egg"]
let ePrefix = streets.prefix { (firstObj) -> Bool in
return firstObj.count > 4
}
print("ePrefix = \(ePrefix)")
}
func useOfRandomElement(){
// Call randomElement() to select a random element from an array or another
collection. This example picks a name at random from an array:
let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
print("Random element = \(randomName)")
}
func useOfMap(){
// A mapping closure. transform accepts an element of this sequence as its
parameter and returns a transformed value of the same or of a different type.
// In this example, map is used first to convert the names in the array to
lowercase strings and then to count their characters.
// map cannot remove nil value
let cast = ["Vivien", "Marlon", "Kim", "Karl", nil]
let lowercaseNames = cast.map { (strObj) -> String in
return (strObj?.lowercased() ?? "a")
}
print("lowercaseNames = \(lowercaseNames)")
let letterCounts = cast.map { $0?.count }
print("letter counts = \(letterCounts)")
}
func useOfCompactMap(){
// A closure that accepts an element of this sequence as its argument and
returns an optional value.
// Use this method to receive an array of non-optional values when your
transformation produces an optional value.
// In this example, note the difference in the result of using map and
compactMap with a transformation that returns an optional Int value.
// flat map also remove nil value but it have convert multiple array into
one array
// compact map also remove nil but it cannot convert multiple array into
one array
func useOfFlatMap(){
let numbers = [[1], [2, 3, 4], [5, 6], [7, 8, 9, 10], nil]
let mapped = numbers.map { (obj) -> [Int]? in
return obj
}
print("Mapped = \(mapped)")
let flatMapped = numbers.flatMap { (obj) -> [Int]? in
return obj
}
let compactMapped = numbers.compactMap { (obj) -> [Int]? in
return obj
}
print("compact mapped = \(compactMapped)")
let againFlat = flatMapped.flatMap { (obj) -> [Int] in
return obj
}
print("flatMapped = \(flatMapped) = \(againFlat)")
func useOfReduce(){
// Use the reduce(_:_:) method to produce a single value from the elements
of an entire sequence. For example, you can use this method on an array of numbers
to find their sum or product.
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(50) { (sum, x) -> Int in
return sum + x
}
print("reduced = \(numberSum)")
}
func useOfForEach(){
// Calls the given closure on each element in the sequence in the same order
as a for-in loop.
//for in
let numberWords = ["one", "two", "three"]
for word in numberWords {
print(word)
}
//for each
numberWords.forEach { (word) in
print(word)
}
}
func useOfEnumerated(){
// Returns a sequence of pairs (n, x), where n represents a consecutive
integer starting at zero and x represents an element of the sequence.
// This example enumerates the characters of the string “Swift” and prints
each character along with its place in the string.
for (index, value) in "Swift".enumerated(){
print("index = \(index), value = \(value)")
}
}
func useOfSorted(){
// Returns the elements of the sequence, sorted.
// You can sort any sequence of elements that conform to the Comparable
protocol by calling this method. Elements are sorted in ascending order.
//
// Here’s an example of sorting a list of students’ names. Strings in Swift
conform to the Comparable protocol, so the names are sorted in ascending order
according to the less-than operator (<).
let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
let descendentStudents = students.sorted { (first, second) -> Bool in
return first > second
}
print(descendentStudents)
func useOfReversed(){
// Returns a view presenting the elements of the collection in reverse
order.
//You can reverse a collection without allocating new space for its elements by
calling this reversed() method. A ReversedCollection instance wraps an underlying
collection and provides access to its elements in reverse order. This example
prints the characters of a string in reverse order:
let word = "Backwards"
func useOfShuffled(){
// Returns the elements of the sequence, shuffled.
// For example, you can shuffle the numbers between 0 and 9 by calling the
shuffled() method on that range:
let numbers = 0...9
let shuffledNumbers = numbers.shuffled()
print("shuffled number = \(shuffledNumbers)")
}
func useOf(){
}
func differenceOfStringAndSubString(){
var greeting = "Hello,world!"
let index = greeting.firstIndex(of:",") ?? greeting.endIndex
var beginning = greeting[..<index]
print(greeting)
greeting = "nagraj"
print(beginning)
// let newGreeting = greeting
// let newBegin = beginning
beginning = "hi hkhkhk hjkh jkjhkj hkhkh hkhkhkhk hkjhkjh hkjhkh hkhkjhk
hkjhkjhkhk"
print(greeting)
print(beginning)
// print(newGreeting)
// print(newBegin)
}
func callPrintFunctions(){
useOfFilter()
}
}