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.

3
  • 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. Commented Aug 14, 2015 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? Commented Aug 14, 2015 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? Commented Aug 14, 2015 at 13:32

1 Answer 1

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" 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man, that solved it!!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.