Swift String Common Method _swift Foundation

Source: Internet
Author: User
Tags lowercase

Refer to the Java String class for a summary of swift string usage.

Basic article:

1, String length: 3 ways.

let-str = "12345678" let
len1 = strlen (str)//8 let
len2 = Str.count  //8 let
len3 = (str as nsstring). Leng Th  //8

2, string concatenation: Use the plus or append function.

Let str1 = "abc" + "CDE"
var str = "abc"
Str.append ("CDE")

3. String Traversal:

Let str = ' ABCDEFG ' for
char in str {
    print (char)
}

Let str = ' ABCDEFG ' for
index in str.indices.indices {
    print (Str[index])   ///through subscript access
}

or subscript

Let str = ' ABCDEFG '
for (index, value) in str.enumerated () {
    print ("\ Index---\ (value)")
}

4, all uppercase or lowercase strings:

Let str = "ABCDEFG"
print (str.lowercased ())  //All lowercase
print (str.uppercased ())  //ALL CAPS

5, multiline string uses 3 double quotes.

let-verse = "" "
    to be, or not to be-that is the question;
    Whether ' tis nobler
    in the mind to suffer the slings and arrows of outrageous fortune,
    or to take arms against Sea of Troubles, "" "" ""


6. ASCII code

Let ASCII = Unicodescalar ("a")?   ASCII code
print (ASCII??) for value//a. "")//97


7. Intercept substring

Let str = ' ABCDEFG ' let
indexd = Str.index (of: ' d ') let
sub = str[indexd!...]//DEFG let
sub1 = Str[indexd!.. <str.endindex]//DEFG  pay attention to avoid subscript out of bounds let
sub2 = str[str.startindex...indexd!]//abcd
Or

Let sub3 = (str as nsstring). substring (to:3)  //abc let
sub4 = (str as nsstring). Substring (With:nsmakerange (2, 3) )  //CDE

8, judge whether contains the character (string)

Let str = "ABCDEFG"
print (Str.contains ("CD"))   //true
print (Str.contains ("C"))    //true
Print (Str.contains ("O"))    //false

9, String segmentation

String splitting (delimited by single or multiple characters) let
str = "abcdefg$ $aaaa $ $BBBB $ $CCC" let
des1 = (str as nsstring). Components (Separatedby : "$$") let
des2 = str.components (separatedby: "$$")
print (des1)  //["ABCDEFG", "AAAA", "bbbb", "CCC"]
Print (Des2)//["ABCDEFG", "AAAA", "bbbb", "CCC"]

10. String Replacement:

Let str = "abcdefg$ $aaaa $ $BBBB $ $ccc ' let
dest11 = str.replacingoccurrences (of: ' $$ ', with:" * * ")
print (dest11)


Advanced Chapter:
1. Get subscript characters:

Extension String {
    //get subscript corresponding character
    func charAt (pos:int)-> Character? {
        If pos < 0 | | | pos >= count {return
            nil   //Judge boundary condition
        } let
        index = Self.index (self.startindex , offsetby:pos) let
        str = self[index] return
        Character (String (str)}} let
str = "ABCdef" C20/>print (Str.charat (pos:1)!)  B

2. Find the longest substring in the string, including Chinese, special characters, letters, numbers, and so on. Idea: use regular to find all the strings, and then sort by length to find the longest.

Find the longest-
func Longestword (_ sen:string)-> string {let
    regx = try? Nsregularexpression (pattern: [a-za-z]+], options:. caseinsensitive)
    
    if let results = regx? Matches (In:sen, Options: [], Range:nsmakerange (0, Sen.count)) {
        var array: [String] = [] for
        item in results {
  let cur = (sen as NSString). substring (with:item.range)
            array.append (cur)  //Find all strings
        that meet the requirements Array.Sort (by: {a,b in
            if A.count > B.count {     //descending order return
                true
            } else {return
                false
            return
        
        array[0]  //Longest string
    } return
    
    sen} let

ret = Longestword (' This is a test demo.1234324234 interspersed with Chinese and special letters @#@ #adfsdfsdf!@#@ $adfsdf ")
print (ret)  //ADFSDFSDF


3. Capitalize the first letter of the string (consider punctuation in the string):

Initials, requiring support for punctuation
func lettercapitalize (_ str:string)-> String {
    
    var result = "" For

    I in 0..<str.count{ Let
        cur = Str.charat (pos:i)

        if i = = 0 {let
            tmp = String (cur!). uppercased ()  //To uppercase
            Result.append (TMP)
        } else {let
            pre = Str.charat (pos:i-1)
            //if pre was not Character
            if (Unicodescalar String (pre!))!. Value >= unicodescalar ("a")!. Value && unicodescalar (String (pre!))!. Value <= unicodescalar ("Z")!. Value)
                | | (Unicodescalar (String (pre!))!. Value >= unicodescalar ("A")!. Value && unicodescalar (String (pre!))!. Value <= unicodescalar ("Z")!. Value) {
                result.append (string (cur!))
            } else {
                result.append (cur!). Uppercased ())}} return result
            
        } let
ret = lettercapitalize (' This a test message ')
Print (ret)


4, get the Uilable control to display the height required by the string

Extension String {
    /**
     * Query lable height
     * @param fontsize, font size
     * @param width, lable width
    * * * func Getlableheightbywidth (_ Fontsize:cgfloat,
                               width:cgfloat,
                               font:uifont)-> cgfloat {let
        size = Cgsize ( Width:width, Height:CGFloat.greatestFiniteMagnitude) let
        paragraphstyle = Nsmutableparagraphstyle ()
        Paragraphstyle.linebreakmode =. bywordwrapping let
        attributes = [Nsfontattributename:font,
                          NSParagraphStyleAttributeName:paragraphStyle.copy ()] let
        
        text = self as nsstring let
        rect = Text.boundingrect (With:size, Options:.useslinefragmentorigin, Attributes:attributes, Context:nil) return
        Rect.size.height
    }
    
}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.