I have a string that looks like this:
https://product/000000/product-name-type-color
I used a split to separate this strings, but Im having problems because the link can come without the description or the id
guard let separateLink = deeplink?.split(separator: "/") else { return }
let linkWithoutProductDetails = "\(separateLink[0] ?? "")//\(separateLink[1] ?? "")/\(separateLink[2] ?? "")"
When the link comes only https://product/
Im getting Fatal error: Index out of range even using the Optionals and String Interpolation, how can i guarantee that independently of the quantity of informations in my link the code wont break
CodePudding user response:
You should check the number of path components. However, ideally you should use the URL
functions instead of manipulating the link as a String
:
if var url = URL(string: "https://product/000000/product-name-type-color") {
let pathComponents = url.pathComponents
// "product" is not a path component, it's the host.
// Path components are "/", "000000" and "product-name-type-color"
if pathComponents.count > 2 {
url = url.deletingLastPathComponent()
}
print(url)
}
CodePudding user response:
To split a string with varied amount of input data, you can use the split() function in Python. This function takes a delimiter as an argument, and returns a list of substrings that are delimited by the specified delimiter.
For example:
data = "apple,banana,orange" fruits = data.split(",") print(fruits)
This will output the following list: ['apple', 'banana', 'orange']
You can also specify a maximum number of splits to be performed by passing an integer as a second argument to the split() function. For example:
data = "apple,banana,orange,mango" fruits = data.split(",", 2) print(fruits)
This will output the following list: ['apple', 'banana', 'orange,mango'], as the split is only performed twice.
Note that the split() function is only effective for splitting strings based on a fixed delimiter. If the input data has a variable number of delimiters, you may need to use a different approach to split the string.