1. String literals
Swift and Java have a similar string operation.
Swift: string literal (string literals): We can include a predefined string value in the code as a string literal. String literals are wrapped in double quotation marks ("") with a fixed-order text character set. String literals can be used to provide initial values for constants and variables.
The code is as follows:
" Some string literal value "
String literals can contain the following special characters:
- Escape character
\0 (null character), (backslash), \\ \t (Horizontal tab), \n (line break), \r (carriage return), \" (double quotation mark), \‘ (single quotation mark).
- A Unicode scalar, written in
\u{n} lowercase (u), which n is any one to eight hexadecimal digits.
Initialize empty string (Initializing an empty string): In order to construct a long string, an empty string can be created as the initial value. You can assign an empty string literal to a variable, or you can initialize a new String instance with the following code:
""= string ()// Initialize string instance // Two strings are both empty and equivalent.
Whether a string in Swift can be modified is determined only by defining a variable or constant, realizing the unification of multiple types of variability operations.
The type of Swift String is a value type. If you create a new string, the value is copied when it is passed in a constant, variable assignment operation, or in a function/method.
Use characters (working with characters): The type of Swift String represents a Character collection of (character) type values for a particular sequence. Each character value represents a Unicode character. You can use for-in loops to iterate through each character in a string, with the following code:
for inch " Dog!?? " { print (character)}// D// o// G// ! // ??
Calculates the number of characters (counting characters) by calling the global countElements function and passing the string as an argument, you can get the number of characters for that string: The code is as follows:
" Koala??, Snail??, Penguin??, dromedary?? " Print ("Unusualmenagerie has \ (Unusualmenagerie. Characters. Count) Characters")
Swift and Java comparison of strings and characters