0

How do I use strstr in Swift to search for a string within a string? I'm not sure how to use UnsafePointer! in Swift. strstr takes two arguments of both that type and returns a value of that type. Is this C or C++? Can I use C or C++ code in Swift, or could I use strstr in Objective-C and use a bridging header?

When I use this code:

var str1 = "Hello"
var str2 = "ll"

var ptr = strstr(str1, str2)

print(ptr)
print(ptr?.pointee)

I get this result:

Optional(0x00006000039bd762)

Optional(0)

Community
  • 1
  • 1
daniel
  • 1,446
  • 3
  • 29
  • 65
  • 6
    Why would you want to do that? There is `str1.range(of: str2)` in Swift. – Martin R Nov 23 '18 at 17:51
  • 1
    I wonder if this is an XY problem. Do you really want to use `strstr()` or is your actual problem how to locate one Swift string within another Swift string? – Martin R Nov 23 '18 at 18:05
  • I need to locate one swift string inside of another swift stream. Your previous comment was what I needed. – daniel Nov 23 '18 at 18:08
  • 1
    Then the title is misleading, and your question is for example answered here: https://stackoverflow.com/questions/32305891/index-of-a-substring-in-a-string-with-swift. – Martin R Nov 23 '18 at 18:09
  • I didn’t think Swift had a way to do it. – daniel Nov 23 '18 at 18:10
  • 1
    This is indeed an XY problem. If you don't know how to accomplish a task in a new language/OS, ask how to accomplish the task at a high level, not how you would accomplish a specific implementation. If we had simply asked the question you asked you would have gone down the wrong coding path. – Duncan C Nov 23 '18 at 18:50
  • @DuncanC What does an XY problem mean? – daniel Nov 24 '18 at 01:04
  • See this link. The first answer is very good: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Duncan C Nov 24 '18 at 02:08
  • 2
    The summary: "The XY problem is asking about your attempted solution rather than your actual problem. That is, you are trying to solve problem X, and you think solution Y would work, but instead of asking about X when you run into trouble, you ask about Y." – Duncan C Nov 24 '18 at 02:09

1 Answers1

3

Swift is a very powerful language. Try out some of its higher level features. Try putting this in playground.

var word = "Hello"
print(String(format: "Word: %@", word))
let range = word.range(of: "ll")!
print(String(format: "Lower Bound: %d", range.lowerBound.encodedOffset))
print(String(format: "Upper Bound: %d", range.upperBound.encodedOffset))

word = word.replacingOccurrences(of: "ll", with: "")
print(String(format: "Word after replacement: %@", word))

for (i, c) in word.enumerated() {
    print(String(format: "Index: %d, Character: %@", i, String(c)))
}
Sethmr
  • 3,046
  • 1
  • 24
  • 42