0% found this document useful (0 votes)
3 views

ChapterString

The document is a Swift class named ChapterString that demonstrates various string manipulation techniques. It includes methods for initializing strings, checking for emptiness, repeating strings, converting between strings and data, and performing various operations like appending, inserting, replacing, and removing characters. Additionally, it covers filtering, dropping elements, and finding substrings and characters within strings.

Uploaded by

zvipin.ahlawat
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

ChapterString

The document is a Swift class named ChapterString that demonstrates various string manipulation techniques. It includes methods for initializing strings, checking for emptiness, repeating strings, converting between strings and data, and performing various operations like appending, inserting, replacing, and removing characters. Additionally, it covers filtering, dropping elements, and finding substrings and characters within strings.

Uploaded by

zvipin.ahlawat
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

// ChapterString.

swift
// VipinSwift

import Foundation

class ChapterString {

func useOfInit(){

//Creates an empty string.


//Using this initializer is equivalent to initializing a string with an
empty string literal.
//both are same
let empty = ""
let alsoEmpty = String()
let checkStr = "hello"
print("Empty = \(empty)")
print("AlsoEmpty = \(alsoEmpty)")
print("checkStr = \(checkStr)")

func useOfInitCharacter(){
//Creates a string containing the given character.
// character take only single value

let characterStr = String("f")


print("character string = \(characterStr)")
let str = String("dfd")
print("string = \(str)")
}

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(){

//A Boolean value indicating whether a string has no characters.


let s = "India"
if s.isEmpty{
print("String is Empty")
}else{
print("String not Empty")
}
//The number of characters in a string.
print("No of characters = \(s.count)")

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

var str = "Hello"


str.append("world")
print("Append String = \(str)")
str.write("seo")
print("write string = \(str)")
}
func useOfWriteTo(){
let str = "Super long string here"
let paths = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)

let filename = paths[0].appendingPathComponent("output.txt")


print(filename)

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.

var numbers = [1, 2, 3, 4, 5]


numbers.append(contentsOf: 10...15)
print("use of append sequence = \(numbers)")
}

func useOfStaticPlus(){
//basically use of concatenation
var lhsStr = "LHS"
let rhsStr = "RHS"
let firstString = lhsStr + rhsStr
print("simple + = \(firstString)")

lhsStr += rhsStr
print("simple += = \(lhsStr)")

// Creates a new collection by concatenating the elements of a sequence and


a collection.
// use a += b in generic function is working but a + b is not working for
string as well as int
var numbers = [1, 2, 3, 4, 5]
// let abc = numbers + 10...15 // could not possible
numbers += 10...15 // but possible
print(numbers)

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

var strArray = ["A", "B", "C", "D"]


strArray.insert("Z", at: 2)
print("insert in string array = \(strArray)")

// Inserts the elements of a sequence into the collection at the specified


position.

var numbers = [1, 2, 3, 4, 5]


numbers.insert(contentsOf: 100...103, at: 3)
print(numbers)
}

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

// Removes all the elements that satisfy the given predicate.


var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll { (first) -> Bool in
return vowels.contains(first)
}

print("remove vowels = \(phrase)")

// Removes and returns the first element of the collection.


var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeFirst()
print("Remove first = \(bugs)")

// Removes the specified number of elements from the beginning of the


collection.
bugs.removeFirst(2)
print("Remove first 2 = \(bugs)")

// Removes and returns the last element of the collection.


var bugsLast = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugsLast.removeLast()
print("Remove last = \(bugsLast)")

// Removes the specified number of elements from the ending of the


collection.
bugsLast.removeLast(2)
print("Remove last 2 = \(bugsLast)")

// Removes the elements in the specified subrange from the collection.


var nums = [10, 20, 30, 40, 50]
nums.removeSubrange(1...3)
print("use with array = \(nums)")

// Removes the characters in the given range.


var strHelloWorld = "Hello world"
let range = strHelloWorld.range(of: "w")
strHelloWorld.removeSubrange(range!)
print("use with strings = \(strHelloWorld)")

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
}
}

print("use of filter = \(abc)")


}

//*
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)")

let cast = ["Vivien", "Marlon", "Kim", "Karl"]


let substring = cast.drop { (obj) -> Bool in
return obj.count > 5
}
print("drop while with array of string = \(substring)")

// Returns a subsequence containing all but the given number of initial


elements.
let dropFirst = strHelloWorld.dropFirst()
print("dropFirst with string = \(dropFirst)")

let dropFirstArray = cast.dropFirst()


print("dropFirst with array string = \(dropFirstArray)")

//dropFirst with parameter


let dropFirstWithParameter = strHelloWorld.dropFirst(5)
print("DropFirst parameter with string = \(dropFirstWithParameter)")

let dropFirstWithParamArray = cast.dropFirst(3)


print("DropFirst parameter with array string = \(dropFirstWithParamArray)")

// Returns a subsequence containing all but the specified number of final


elements.
let dropLast = strHelloWorld.dropLast()
print("dropLast with string = \(dropLast)")

let dropLastArray = cast.dropLast()


print("dropLast with array string = \(dropLastArray)")

//dropLast with parameter


let dropLastWithParameter = strHelloWorld.dropLast(5)
print("DropLast parameter with string = \(dropLastWithParameter)")

let dropLastWithParamArray = cast.dropLast(3)


print("DropLast parameter with array string = \(dropLastWithParamArray)")

// Removes and returns the last element of the collection.


// popLast returns nil if the collection is empty.
// removeLast crashes if the collection is empty. It also has a discardable
result.
var fullString = "Hello World Atlas"
let popLastString = fullString.popLast()
print("full with string = \(fullString)")
print("popLast with string = \(popLastString)")

var fullStrArray = ["Vivien", "Marlon", "Kim", "Karl"]


let popLastObj = fullStrArray.popLast()
print("full with string array = \(fullStrArray)")
print("poplast with string array = \(popLastObj)")

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

let namesArray = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]


let allHaveAtLeastFiveArray = namesArray.allSatisfy { (strObj) -> Bool in
return strObj.count >= 5
}

print("Bool array = \(allHaveAtLeastFiveArray)")


}

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

// Returns the first index in which an element of the collection satisfies


the given predicate.
if let i = students.firstIndex(where: { (strObj) -> Bool in
return strObj.hasPrefix("J")
}){
print("first object string start with J = \(students[i])")
}

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

let possibleNumbers = ["1", "2", "three", "///4///", "5", nil]


let mapped : [Int?] = possibleNumbers.map { (strObj) -> Int? in
return Int(strObj ?? "a")
}
print("Mapped = \(mapped)")
let compactMapped : [Int] = possibleNumbers.compactMap { (strObj) -> Int?
in
return (Int(strObj ?? "a"))
}
print("compact Mapped = \(compactMapped)")
}

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

let numbers1 = [[1], [2, 3, 4], [5, 6], [7, 8, 9, 10]]


let mapped1 = numbers1.map { (obj) -> [Int] in
return obj
}
print("Mapped1 = \(mapped1)")
let flatMapped1 = numbers1.flatMap { (obj) -> [Int] in
return obj
}
let compactMapped1 = numbers1.compactMap { (obj) -> [Int] in
return obj
}
print("compact mapped1 = \(compactMapped1)")
let againFlat1 = flatMapped1.flatMap { (obj) -> Int in
return obj
}
print("flatMapped1 = \(flatMapped1) = \(againFlat1)")

let numbers2 = [1, nil, 2,5,6]


let mapped2 = numbers2.map { (obj) -> Int? in
return obj
}
print("Mapped2 = \(mapped2)")
let flatMapped2 = numbers2.flatMap { (obj) -> Int? in
return obj
}
let compactMapped2 = numbers2.compactMap { (obj) -> Int? in
return obj
}
print("compact mapped2 = \(compactMapped2)")
let againFlat2 = flatMapped2.flatMap { (obj) -> Int in
return obj
}
print("flatMapped2 = \(flatMapped2) = \(againFlat2)")

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)

let abs = students.sorted(by: { $0 > $1})


let bfg = students.sorted { (f, s) -> Bool in
if f.count > 5{
return f > s
}else{
return s > f
}
}
print(bfg)

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"

for char in word.reversed(){


// print(char, terminator: "")
print(char)
}
let reversedWord = String(word.reversed())
print(reversedWord)
}

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()
}
}

You might also like