Declaring a string
var"Hello, playground" //声明一个字符串var""; //声明一个空的字符串varString(); //相等于上面的那个
str.isEmpty; //判断str是不是为空falseemptyStr.isEmpty; //true
String connection
var"hello";var"world";var str = str1 + str2;
Print each character in a string
forcharacterin str.characters { print(character);}
declaring characters
let"a"//‘a‘是错误的let cat:[Character] = ["c""a""t""!"]; //声明一个字符数组letString(cat); //将字符数组变为字符串
Append character after string
let"a";catStr.append(c);
string interpolation
You can use the "(value)" method to insert a value into a string to construct a new string
letInt40;let"我有\(someNum)包茶叶";
String contains the number of characters
num = message.characters //message字符串含有的字符
Accessing and modifying strings using subscript access
Let greet ="Good Morning";/*startindex represents the starting subscript for the string * /Greet[greet. StartIndex];/*endindex represents the end of the string below predecessor represents the previous * /Greet[greet. EndIndex. Predecessor()];/*successor Strap continues to be the next one * /Greet[greet. StartIndex. Successor()];/ * String does not support direct access to subscript, need to use advance function conversion, if access to the subscript outside the string will emit a run-time error * /Let index = advance (greet. StartIndex,7);Greet[index];greet[7]//Syntax error Greet[greet. EndIndex]; ErrorGreet[greet. EndIndex. Successor()]; Error
Create a subscript range using indices
forin indices(greet) { print("\(greet[index])");}
Adding and removing elements into a string
–
var greet ="Hello";/ * Insert a character using the insert */Greet. Insert("!", Atindex:greet. StartIndex);/ * Insert character groups using splice * /Greet. Splice("World". Characters, Atindex:greet. EndIndex);/*removeatindex Remove Characters in a subscript * /Greet. Removeatindex(Greet. StartIndex);/ * Create a range, then remove the range * /Let range = Advance (greet. StartIndex,5).. <greet. EndIndex;Greet. RemoveRange(range);
string comparison
let"hello";let"hello"str1 == str2; //比较两个字符串是否相等
let strs = ["hello""morning""happy"];forstr in strs {//判断字符串开头是否包含he if(str.hasPrefix("he")) { print(str);//判断字符串结尾是否包含ng }elseifstr.hasSuffix("ng") { print(str); }}
"Swift Summary" string and character