如何从Swift 1.2中的字符串中提取字符串?

时间:2015-04-27 07:52:15

标签: string swift ios8

我有一串类型:" Lorem ipsum dolor sit amet,他的ipsum maiestatis in,in eapo sapientem temporibus,ea reque accumsan euripidis vis。 Posse consectetuer te,te per possit gloriatur" TEN_WHITE_SPACES" constituto,et ius amet feugiat dolores。 Eam simul nominavi et,graece tractatos qui ea,vim nisl lucilius contentiones ne。" SIX_WHITE_SPACES" Movet labores ex sed,detracto platonem splendide an est,postea fastidii eos ex。 Iudico regione diceret mei no,ei homero fuisset voluptaria nec,has modus sadipscing ei。"

字符串:" constituto,et ius amet feugiat dolores。 Eam simul nominavi et,graece tractatos qui ea,vim nisl lucilius contentiones ne。"用开头分隔:“”(10个空格)和结尾:“"(6个空格)是我需要提取和加粗的标题。 我可以使用 NSAttributedString 进行粗体部分,但是我无法找出提取部分。

我为Swift 1.2尝试了以下SO解决方案:

ERROR: Cannot invoke 'Split' with an argument list of type '((String)),'...

//fullName is declared somewhere alse as NSString, then as String but always the same error
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

如果我使用:

var fullName = "First Last and bla bla bla..."

它以某种方式起作用......但是当使用预定义的变量时,它并没有。

我也尝试过: Full split function...

let bits = split(fullName, maxSplit: Int.max, allowEmptySlices: false,
             isSeparator: { $0 == " "})

并得到类似的错误:"无法调用..."

我也尝试过使用:

var allContentStringsBeforeBoldTextArray = temporaryContent.componentsSeparatedByString("              ")
    var boldContent = allContentStringsBeforeBoldTextArray[0].componentsSeparatedByString("        ")

    println(" String count   \(allContentStringsBeforeBoldTextArray.count)")
    println(" Bold string count   \(boldContent.count)")

而不是得到数组计数2我得到arrayCount = 1,在某处我丢失了另一半的字符串。

老实说,我不能相信,对于一个简单的对象,比如String(一个字符数组),apple有很多类......来自String,NSString,NSAttributedString。并且这些类中的每一个对于相同的操作都没有相同的方法名称。我是Swift的新手,但它过于复杂。

更新1

测试代码:

    override func viewDidLoad()
{
    super.viewDidLoad()

    // goal string = "HEADER"

    var startingStringSeparator = "          " // 10 whitespaces
    var endingHeaderSeparator = "      " // 6 whitespace

    var exampleStringNS:NSString = "Lorem ipsum dolor sit amet, his in ipsum latine, duo no quod vocent delenit. Mei nibh eros ut, elit ancillae ei cum,          HEADER      omnium cotidieque liberavisse his te. Aeque elitr ne cum, vis eu cibo ornatus alienum."

     var exampleStringSwift:String = "Lorem ipsum dolor sit amet, his in ipsum latine, duo no quod vocent delenit. Mei nibh eros ut, elit ancillae ei cum,          HEADER      omnium cotidieque liberavisse his te. Aeque elitr ne cum, vis eu cibo ornatus alienum."

    // *
    // 1. TEST RUN

    var splitResultString = split(exampleStringSwift as String) {$0 == startingStringSeparator}
    // ERROR: Cannot invoke split with argument list of type (String,(...)->...)"    
    // *

    // **
    // 2. TEST RUN
    var fullName = "First Last and bla          bla bla..."
    var fullNameArr = split(fullName) {$0 == " "}
    var firstName: String = fullNameArr[0]
    var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

    println(firstName)
    println(lastName)
    // OUTPUT LINE1: First
    // OUTPUT LINE2: Optional("Last")
    // **

    //***
    // 3. TEST RUN - same as TEST RUN 2 but with 10 whitespaces

    var fullNameArr1 = split(fullName) {$0 == "          "}
    var firstName1: String = fullNameArr1[0]
    var lastName1: String? = fullNameArr1.count > 1 ? fullNameArr1[1] : nil

    println(firstName1)
    println(lastName2)
    // ERROR: Cannot invoke split with argument list of type (String,(...)->...)"
    // ***

}

更新2:

一般工作解决方案:

    override func viewDidLoad()
{
    super.viewDidLoad()

    // goal string = "HEADER"

    var startingStringSeparator = "          " // 10 whitespaces
    var endingHeaderSeparator = "      " // 6 whitespace

    var exampleStringNS:NSString = "Lorem ipsum dolor sit amet, his in ipsum latine, duo no quod vocent delenit. Mei nibh eros ut, elit ancillae ei cum,          HEADER      omnium cotidieque liberavisse his te. Aeque elitr ne cum, vis eu cibo ornatus alienum."

    var exampleStringSwift:String = "Lorem ipsum dolor sit amet, his in ipsum latine, duo no quod vocent delenit. Mei nibh eros ut, elit ancillae ei cum,          HEADER      omnium cotidieque liberavisse his te. Aeque elitr ne cum, vis eu cibo ornatus alienum."

    // *
    // 1. TEST RUN

    var exampleStringNS_Arr = exampleStringSwift.componentsSeparatedByString(startingStringSeparator)
    var exampleStringNS_BoldText_Arr = exampleStringNS_Arr[1].componentsSeparatedByString(endingHeaderSeparator)

    println(exampleStringNS_Arr[0])
    println(exampleStringNS_Arr[1])

    println(" **** ")
    println(exampleStringNS_BoldText_Arr[0])
    println(" **** ")
    //
    // *
}

此解决方案有效,但不是我的情况。原因是我的JSON解析文本格式不一致。我使用的是错误的方法。 split只能基于一个char进行拆分,而不是一个chars数组(string)。感谢@Martin R清除它并指出我正确的方向。

1 个答案:

答案 0 :(得分:0)

您可以使用substringWithRange方法。它需要一个开始和结束String.Index。

var str = "Hello, playground"
    str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground

你仍然可以在NSRange中使用NSString方法,但你必须确保使用这样的NSString:

let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 0, length: 3))

试试这个。这可以帮助您从字符串中提取字符串。

编辑过的部分你将获得角色的位置

var loc = "abcdefghi".rangeOfString("c").location
NSLog("%d", loc);

这也有效,

var myRange: NSRange = "abcdefghi".rangeOfString("c")
var loc = myRange.location
NSLog("%d", loc);