swift * string - String

1. Statement

There are two ways to declare variables in swift: immutable constant let declaration and mutable variable var declaration.

Strings are the same

let constantString:String = "string test" // This declaration means that the string is immutable, it is only used, and cannot be added, deleted, modified or checked.

var variableString:String = "variable string" //Variable string is equivalent to NSMutableString in OC 

Of course, all variables in swift will automatically determine their type according to the assigned value, so you don't need to display the declared type when you declare it.

let constantString= "constant string"

var variableString = "variable string"

2. Common methods

var variableString = "Variable ? ? ? String ? !"

1), isEmpty //Verify whether the string is empty

variableString.isEmpty //return true / false (true and false in swift)

2), judge pre/post

variableString.hasPrefix("var")  // 返回 true /false 

variableString.hasSuffix("string") //返回 true /false 

3), string case

let capitalize = variableString.capitalizedString //Convert all letters to lowercase letters, the original string remains unchanged 

let uppercase = variableString.uppercaseString // Convert all letters to uppercase, the original string remains unchanged

4), delete the specified character

let trimString = variableString.stringByTrimmingCharacterInSet(NSCharacterSet(charactersInString:"?"))

If it is to remove spaces 

let trimString1 = variableString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

5), split

Similar to OC, split according to a specified character and return an array type

let strArr = variableString.componentsSeperatedByString(" ")

6), splicing 

var insertString = "-"

insertString.join(["a","b","c"]) //结果"a-b-c"

7), the query string contains the specified string

var variableString = "Variable ? ? ? String ? !"

let range = variableString.rangeOfString("string") // 15..<21 This method returns the position of the first occurrence of the specified string from left to right, if it does not exist, it returns nil


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325892411&siteId=291194637