-5

how can I substring the next 2 characters of a string after a certian character. For example I have a strings str1 = "12:34" and other like str2 = "12:345. I want to get the next 2 characters after : the colons. I want a same code that will work for str1 and str2.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Unique LoL Apps
  • 88
  • 1
  • 11
  • 2
    Possible duplicate of [How does String substring work in Swift 3](http://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift-3) – sschale Mar 12 '17 at 17:12
  • i dont know why i am getting down votes, I can do it pretty easy in Java but in swift I am trying for 3 hours without a success – Unique LoL Apps Mar 12 '17 at 17:12
  • @sschale Ive seen that thread but in my case I can't use Range with endindex having a constant "offsetBy" value because my endIndex is different at the both strings – Unique LoL Apps Mar 12 '17 at 17:15

3 Answers3

1

Swift's substring is complicated:

let str = "12:345"

if let range = str.range(of: ":") {
    let startIndex = str.index(range.lowerBound, offsetBy: 1)
    let endIndex = str.index(startIndex, offsetBy: 2)
    print(str[startIndex..<endIndex])
}
Mike Henderson
  • 2,028
  • 1
  • 13
  • 32
  • ahhh thanks, i couldnt think of it, ive been searching for 3 hours and i couldnt find. thanks a lot – Unique LoL Apps Mar 12 '17 at 17:17
  • 2
    @UniqueLoLApps Simply googling "Swift substring" yields a top result which is an SO question with 57 votes, 7 answers, and plenty of clear explanations on the topic. – Alexander Mar 12 '17 at 17:28
0

It is very easy to use str.index() method as shown in @MikeHenderson's answer, but an alternative to that, without using that method is iterating through the string's characters and creating a new string for holding the first two characters after the ":", like so:

var string1="12:458676"
var nr=0
var newString=""
for c in string1.characters{
    if nr>0{
        newString+=String(c)
        nr-=1
    }
    if c==":" {nr=2}
}
print(newString) // prints 45

Hope this helps!

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
0

A possible solution is Regular Expression,

The pattern checks for a colon followed by two digits and captures the two digits:

let string = "12:34"
let pattern = ":(\\d{2})"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.characters.count)) {
    print((string as NSString).substring(with: match.rangeAt(1)))
}
vadian
  • 274,689
  • 30
  • 353
  • 361