To get the substring before a specific character in Swift, you can use the `prefix` method.
In this example,
url
with a value of "https://example.com/page"
.prefix
method with the index of '/' to get the substring before the specified character.let url = "https://example.com/page"
let index = url.firstIndex(of: "/") ?? url.endIndex
let substring = url.prefix(upTo: index)
print("Substring before '/':", substring)
Substring before '/': https:
In this example,
str
with a value of "Hello,World"
.prefix
method with the index of ',' to get the substring before the specified character.let str = "Hello,World"
let index = str.firstIndex(of: ",") ?? str.endIndex
let substring = str.prefix(upTo: index)
print("Substring before ',':", substring)
Substring before ',': Hello
In this tutorial, we learned How to get Substring before Specific Character in Swift language with well detailed examples.