-1

I hava string of type : "Lorem ipsum dolor sit amet, his ipsum maiestatis in, has in odio sapientem temporibus, ea reque accumsan euripidis vis. Posse consectetuer te his, 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."

The string :"constituto, et ius amet feugiat dolores. Eam simul nominavi et, graece tractatos qui ea,vim nisl lucilius contentiones ne." which is separated with the begining:“ “(10 whitespaces) and ending:“ "(6 whitespaces) is a header which I need to extract and bold. The bolding part I can do with NSAttributedString, however I can't figure out the extraction part.

I tried the following SO solutions for Swift 1.2:

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

If instead I use :

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

It somehow works... but when using a predefined varible it doesn't.

I also tried: Full split function...

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

And get a similar error: "Cannot invoke..."

I also tried using:

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

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

And instead of getting a array count of 2 I get arrayCount = 1, somewhere I lose the other half of the string.

Honestly I can't belive that for one simple object like a String (an array of characters) apple has so many classes... from String, NSString, NSAttributedString. And each one of these classes does not have the same method name for the same operation. I am new to Swift but it is overcomplicated.

UPDATE 1

Test code:

    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,(...)->...)"
    // ***

}

UPDATE 2:

General working solution:

    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(" **** ")
    //
    // *
}

This solution works, but not in my case. The reason is that my JSON parsed text in not consistently formatted. I was using the wrong method. split can only split based on one char, not an array of chars (string). Thanks @Martin R for clearing that out and pointing me in the right direction.

Community
  • 1
  • 1
MB_iOSDeveloper
  • 4,178
  • 4
  • 24
  • 36
  • *"It somehow works... but when using a predefined varible it doesn't."* Can you post a (small) *self-contained* example which demonstrates the problem? – *"And get a similar error: "Cannot invoke...""* Please post the full exact error messages. – Martin R Apr 27 '15 at 07:56
  • Your first example should all work if `fullNameArr` is a Swift String. If it is an NSString, then you have to convert it explicitly, e.g. `var fullNameArr = split(fullName as String) {$0 == " "}` . – Martin R Apr 27 '15 at 07:59
  • Reading your question again it seems to me that `split()` is the wrong tool here. It might be better to use `rangeOfString` to find TEN_WHITE_SPACES/SIX_WHITE_SPACES or use regular expressions. Perhaps you can use this: http://stackoverflow.com/a/29602677/1187415. – Martin R Apr 27 '15 at 08:05
  • Ok, using: var allContentStringsBeforeBoldTextArray = split(contetConvertedString as String) {$0 == " "} gives me the error: "Cannot invoke split with argument list of type (String,(...)->...)" – MB_iOSDeveloper Apr 27 '15 at 08:08
  • What I meant is a *self-contained* example: Some code lines which I can copy into my Xcode project and reproduce the problem. Please add that to your question, not in the comments, thanks! – Martin R Apr 27 '15 at 08:10
  • I updated the answer. You can copy the code in a new project and comment out lines for the particular test case. – MB_iOSDeveloper Apr 27 '15 at 08:28
  • 2
    OK, now you have shown the real problem. `split(exampleStringSwift as String) {$0 == startingStringSeparator}` does not work because `split()` can only separate on *single characters*, not on strings. As I said above, it is probably the wrong tool here. – Martin R Apr 27 '15 at 08:31
  • Thank you. This was the answer I was looking for. The Error description wasn't helpfull at all. Now I also used componentsSeparatedByString. I will update the code. – MB_iOSDeveloper Apr 27 '15 at 08:34

1 Answers1

0

You can use the substringWithRange method. It takes a start and end String.Index.

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

You can also still use the NSString method with NSRange, but you have to make sure you are using an NSString like this:

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

try this one. This may help you to extract the string from a string.

edited part u will get the location of the character

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

this worked too,

var myRange: NSRange = "abcdefghi".rangeOfString("c")
var loc = myRange.location
NSLog("%d", loc);
SARATH SASI
  • 1,395
  • 1
  • 15
  • 39
  • I already did such a thing , but in this case I would need to find the correct location of the string. Could you edite the answer with a function to find the index? I am currently trying to get the split function to work, if it is possible (for my case) – MB_iOSDeveloper Apr 27 '15 at 08:28
  • I will try it. Hope it works for "ccc" (multiple chars). – MB_iOSDeveloper Apr 27 '15 at 09:28
  • var str:String = "Hello, playground" let range = Range(start:advance(str.startIndex,1), end:advance(str.startIndex,8)) //it will return you "ello, p" – SARATH SASI Apr 27 '15 at 09:38