0

Could someone pls tell me how i get a subString from a String? I tried everything with substring and rangeOfString methods but can't solve it... My text goes like this:

var text = "Suuuuper, {1} has sent {2} a very cool present"

My text can vary before {1} and after {2}, so I suppose I have to first get always the indexes of "{1}" and "{2}" and then get substrings.

I would like to have in the end:

var myTextBefore{1}: String = ...

var myTextAfter{2}: String = ...

Thanks in advance.

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
S. Birklin
  • 1,255
  • 1
  • 13
  • 19
  • 2
    `I tried everything with substring and rangeOfString methods` - Can you show us these efforts? Maybe we can point out what's wrong with them. – James Webster Aug 14 '15 at 13:28
  • {1} and {2} what are they, it will be like this or it will replace with some names? iwhat will be the format will it be like {name1} or name1? – Adnan Aftab Aug 14 '15 at 13:32
  • Just a side note: This looks like your trying to input some names into a notification body. Why not just use a formatted string? – James Webster Aug 14 '15 at 13:32

1 Answers1

3

You can use rangeOfString, substringToIndex and substringFromIndex methods:

let text = "Suuuuper, {1} has sent {2} a very cool present"
let myTextBefore1 = text.substringToIndex(text.rangeOfString("{1}")!.startIndex) // "Suuuuper, "
let myTextAfter2 = text.substringFromIndex(text.rangeOfString("{2}")!.endIndex) // " a very cool present"
Kirsteins
  • 27,065
  • 8
  • 76
  • 78