Basic String Operations
Basic String Operations
-
Creating Strings: You can create strings using double quotes, like
"Hello, world!". Swift also allows multi-line strings using triple quotes, which is useful for longer texts or code snippets. -
Concatenation: To combine strings, you use the
+operator. For example,"Hello" + " " + "World"results in"Hello World". You can also use string interpolation with\()to insert variables or expressions inside strings, such as"The score is \(score)". -
Appending: You can add more text to an existing string using the
append()method or the+=operator. For example,myString.append(" Text")ormyString += " Text"will add" Text"tomyString. -
Length: To find out how many characters are in a string, use the
countproperty, likemyString.count, which gives you the number of characters. -
Accessing Characters: Swift strings are indexed by integer positions. To access a character at a specific position, use
myString[index], whereindexis the position you’re interested in. For example,myString[myString.index(myString.startIndex, offsetBy: 2)]accesses the third character ofmyString. -
Substrings: You can extract parts of a string using ranges. For example,
myString[myString.startIndex..<myString.index(myString.startIndex, offsetBy: 5)]gets the first five characters. -
Uppercase and Lowercase: Convert strings to all uppercase or lowercase using
uppercased()andlowercased()methods, like"hello".uppercased()which gives"HELLO". -
Trimming: Remove unwanted spaces from the beginning and end of a string with
trimmingCharacters(in: .whitespaces), useful for cleaning up user input. -
Checking Prefixes and Suffixes: Use
hasPrefix(_:)andhasSuffix(_:)to check if a string starts or ends with a particular substring.
Comments
Post a Comment