您的位置:首页 > 移动开发 > Swift

swift学习之路(六)字符串和字符的常用操作

2016-05-30 20:18 381 查看
字符和字符串的常用操作包括连接,复制,比较,删除,插入。

(一)连接

连接比较简单,只需要用+就能将他们连接起来,不过值得注意的是单个字符常量或变量只能表示一个字符以及常量和变量的使用。

example:

import Foundation

let leftName = "hello "

let rightName = "world"

var thisName =
leftName + rightName

print(thisName)

(二)比较

    1、比较两个字符串是否相等可以用“==”操作符。

example:

import Foundation

let str1 =
"hello world"

let str2 =
"hello world"

if str1 ==
str2 {

print("str1 is full equal to str2")

    

}

    2、通过调用string类型的hasPrifix/hasSuffix方法检查字符串是否拥有特定的前缀/后缀。

example:

import Foundation

var exceptionLogs = [

"warning: Login In System with no passworld Check By DB",

"warning: View customer list without DB",

"Error: You Have No Jusrisdiction",

"warning: A Operate is no effect",

"Error: Illicit close is no effect"]

var warningCount =
0

var ErrorCount = 0

for attile
in exceptionLogs{

    if attile.hasPrefix("warning"){

    warningCount++

    }

    if attile.hasPrefix("Error"){

    ErrorCount++

    }

}

print("warning has
\(warningCount) and error has
\(ErrorCount)")//输出3,2

var DBcount = 0;

for attile
in exceptionLogs{

    if attile.hasSuffix("Check By DB"){

    DBcount++

    }

}

print("have
\(DBcount) checked by DB")//输出1

    string类型拥有uppercaseString 和 lowercaseString两个属性,使用它们来访问一个字符串的大写\小写版本。   example:

import Foundation

let str1 = "ABCDE"

let str2 = "abcde"

var str3 =
str1.lowercaseString

if str3 ==
str2{

print("they are equal")

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift