swift 对字符串的一些处理

这篇博客介绍了Swift中处理字符串的各种方法,包括从数组中筛选最长字符串、字符串加粗和颜色显示、取小数点后部分、查找字符位置、统计字符个数、判断包含、计算宽高、去掉数字前的0、去除两端特殊符号、拆分字符串为数组以及截取字符串等实用技巧。
摘要由CSDN通过智能技术生成

从字符串数组中筛选最长字符串

func getLongestStringFromArray(strArray:NSArray)->String
{
    var string = ""
    for(var j=0;j<strArray.count;j += 1)
    {
        if(strArray[j].length > string.length)
        {
            string = strArray[j] as! String
        }
    }
    return string
}

字符串部分加粗显示

func changePartOfStringToBold(allString:String,boldString:String,fontSize:CGFloat)->NSMutableAttributedString
{
    let attriStr:NSMutableAttributedString = NSMutableAttributedString(string:allString)
    let boldRange = NSMakeRange(NSString(string: allString).rangeOfString(boldString).location, NSString(string: allString).rangeOfString(boldString).length)
    attriStr.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: fontSize)!, range: boldRange)
    return attriStr
}

字符串部分字符显示不同颜色

func changePartOfStringStyle(allString:String,rangeString:String,isBold:Bool,fontSize:CGFloat)->NSMutableAttributedString
{
    let attriStr:NSMutableAttributedString = NSMutableAttributedString(string:allString)
    let range = NSMakeRange(NSString(string: allString).rangeOfString(rangeString).location, NSString(string: allString).rangeOfString(rangeString).length)
    attriStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: (range ))
    if(isBold == true)
    {
        attriStr.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: fontSize)!, range: range)
    }
    return attriStr
}

取字符串某一个字符后的部分(如:小数点后的字符)

let str = "13.123"
let strArray = str.componentsSeparatedByString(".")
let str2 = Array[1]

查找指定字符位置,及获得指定范围的子字符串   


let source = "abcdefg"
let str = "c"
let range = NSMakeRange(2, 1)


let subRange = (source as NSString).rangeOfString(str)   //子范围
let subString = (source as NSString).substringWithRange(range)  //子字符串

统计字符串中某一字符个数

let string = "121314"
let subString = "1"
let array = string.components(separatedBy: subString)
let count = array.count - 1
print("数量是 \(count)")

判断字符串是否包含另一字符串

func isContainSubString(string:String,subString:String) -> Bool{
    if string.componentsSeparatedByString(subString).count > 1 {
        return true
    } else {
        return false
    }
}

获取字符串的宽高

func getTextRectSize(text:NSString,font:UIFont,size:CGSize) -> CGRect

{

let attributes = [NSFontAttributeName: font]

let option = NSStringDrawingOptions.UsesLineFragmentOrigin

let rect:CGRect = text.boundingRectWithSize(size, options: option, attributes: attributes, context: nil)

let viewRect:CGRect = CGRectMake(0, 0, rect.width + 1, rect.height + 1)

return viewRect

}

一般用来动态计算label的高度,也可用于多个label对齐时,计算最长的label的宽度,例:

let str = "我来举个栗子,我来举个栗子,我来举个栗子,我来举个栗子,我来举个栗子,我来举个栗子,我来举个栗子,我来举个栗子,我来举个栗子"

let labHeight:CGFloat = getTextRectSize(str as NSString, font: UIFont.systemFont(ofSize: 14), size: CGSize(width:320,height:1000)).height

print(labHeight)

多样性字符串

func changePartOfStringStyle(_ allString:String,rangeString:String,isBold:Bool,fontSize:CGFloat,textColor: UIColor)->NSMutableAttributedString

{

let attriStr:NSMutableAttributedString = NSMutableAttributedString(string:allString)

let range = NSMakeRange(NSString(string: allString).range(of: rangeString).location, NSString(string: allString).range(of: rangeString).length)

attriStr.addAttribute(NSForegroundColorAttributeName, value: textColor, range: (range ))

attriStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: fontSize), range: range)

if(isBold == true)

{

attriStr.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: fontSize)!, range: range)

}

return attriStr

}

一般用来实现label中的字,有不同的font、color等。例:

let priceLabel = UILabel()

let price:String = "1000"

let priceAtt = changePartOfStringStyle("价格:\(price) 元", rangeString: "\(price)", isBold: false, fontSize: 12, textColor: UIColor.red)

priceLabel.attributedText = priceAtt

去掉数字字符串前的 “0”

func getTheCorrectNum(tempString:String) -> String {

var temp:NSString = NSString(string:tempString)

while temp.hasPrefix("0") {

temp = temp.substring(from: 1) as NSString

}

return String(temp)

}

去除字符串两端的特殊符号

func trimString(_ string:String) -> NSString{

let set:CharacterSet = CharacterSet(charactersIn:"@!= ")

let cleanString = NSString(string:string.trimmingCharacters(in: set))

return cleanString

}

一般用于过滤用户在输入框输入不合法的字符,例:

let str2 = "@我又来举栗子= !"

print(trimString(str2))

打印:我又来举栗子

字符串拆分为数组

func getImageArray(_ pic:String) -> NSArray{

let array = pic.components(separatedBy: ";")

return array as NSArray

}


截取字符串后几位

let str = "HelloWorld"
let subStr = NSString(string:str).substring(from: NSString(string:str).length - 5)




附:

去除数组中重复数据的几种方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值