0

I want to cut several substrings out of a string, which are always between two whitespace, in order to use them further. but I get an extra sign (" ") at the end ... What am I doing wrong? Who can help?

let text = "123045 7890 842 abcde fghij"
var index4Blank = text.index(of: " ")   // first 'blank'
index4Blank?.encodedOffset

// Find NEXT/last occurance of " "
if let rangeOfBlank = text.range(of: " ", options: .backwards) {
  // Get the characters between first 'blank' and next 'blank'
  let suffix = text[index4Blank!..<rangeOfBlank.upperBound] // "7890 "
  print(suffix)
}

what I want: "123045" and "7890" and "842" and "abcde" and "fghij" ((Sorry for the question, but I'm really a beginner in Swift))

Neu4Swift
  • 315
  • 4
  • 10

2 Answers2

3
let text = "123045 7890 842 abcde fghij"
var textArr = text.components(separatedBy: " ") // For swift 3+
var textArr = text.split(separator: " ") // For swift 4
print(textArr)

You can get substrings using this code in array called "textArr".

Punit
  • 1,330
  • 6
  • 13
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/350567) by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – iBug Jan 09 '18 at 10:01
  • Thank you - but then I get the message: Use of unresolved identifier 'split'. What am I missing there? – Neu4Swift Jan 11 '18 at 01:29
0

To answer your question literally:

  • index(of: – as the name implies – returns the index of the first character of the found string, in your case the space character after 123045
  • range(of: ... ).upperBound returns the index of the character after the found string so the last space character is included.

To remove the leading and trailing whitespace with your code you have to use lowerBound for the upper bound and range(of: calling upperBound for the lower bound.

let text = "123045 7890 842 abcde fghij"
if let index4Blank = text.range(of: " "),

    // Find NEXT/last occurance of " "
    let rangeOfBlank = text.range(of: " ", options: .backwards) {
    // Get the characters between first 'blank' and next 'blank'
    let suffix = text[index4Blank.upperBound..<rangeOfBlank.lowerBound] // "7890 "
    print(suffix)
}

However to split a string into parts by a given separator there are better ways like in the other answer or here

vadian
  • 274,689
  • 30
  • 353
  • 361