swift 对字符串的一些处理

前端之家收集整理的这篇文章主要介绍了swift 对字符串的一些处理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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,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)  //子字符串



猜你在找的Swift相关文章