How to extract phrase from string using Range? [duplicate] - ios

This question already has answers here:
Finding index of character in Swift String
(33 answers)
Closed 6 years ago.
This sounds easy, but I am stumped. The syntax and functions of Range are very confusing to me.
I have a URL like this:
https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post
I need to extract the part #global-best-time-to-post, essentially the # to the end of the string.
urlString.rangeOfString("#") returns Range
Then I tried doing this assuming that calling advanceBy(100) would just go to the end of the string but instead it crashes.
hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100))

Easiest and best way to do this is use NSURL, I included how to do it with split and rangeOfString:
import Foundation
let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
// using NSURL - best option since it validates the URL
if let url = NSURL(string: urlString),
fragment = url.fragment {
print(fragment)
}
// output: "global-best-time-to-post"
// using split - pure Swift, no Foundation necessary
let split = urlString.characters.split("#")
if split.count > 1,
let fragment = split.last {
print(String(fragment))
}
// output: "global-best-time-to-post"
// using rangeofString - asked in the question
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex {
// Note that I use the index of the end of the found Range
// and the index of the end of the urlString to form the
// Range of my string
let fragment = urlString[endOctothorpe..<urlString.endIndex]
print(fragment)
}
// output: "global-best-time-to-post"

You could also use substringFromIndex
let string = "https://github.com..."
if let range = string.rangeOfString("#") {
let substring = string.substringFromIndex(range.endIndex)
}
but I'd prefer the NSURL way.

use componentsSeparatedByString method
let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post"
let splitArray = url.componentsSeparatedByString("#")
your required last text phrase (without # char) will be at the last index of the splitArray , you can concatenate the # with your phrase
var myPhrase = "#\(splitArray[splitArray.count-1])"
print(myPhrase)

Related

How to separate two URLs in a String in Swift?

What is the best way to split this String into two using Swift?
"https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
I only need the second part of url in the String. In this example, in this case I just need:
"http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
let str = "https://apod.nasa.gov/apod/http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif"
if let lastStr = str.components(separatedBy: "http").last
{
let result = "http" + lastStr
print(result)
}
Console Output: http://nusoft.fnal.gov/nova/public/img/FD-evt-echo.gif

Syntax to put a variable in a string in swift3

A question I think pretty simple but I never had to do it in swift. it's pretty simple PHP but here I do not find my solution on the internet.
ask: I would like to add a variable in this chain of character. Instead of 123, I would need a variable.
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_123.json"
result = final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_VARAIBLE.json"
Can you give me the syntax in swift3 or direct me to a good tutorial.
You can create a string using string formatting.
String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"
\(variable) is what you need
OR
use string formatting
let variable = 123
final let urlString = String(format:"https://ozsqiqjf.preview.infomaniak.website/empdata_%d.json", variable)
There is good documentation about Strings in Swift Language Guide. Your options are:
Concatenating Strings
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + value + ".json"
String interpolation
let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(value).json"
Swift4 You can add a string in these ways:
var myString = "123" // Or VARAIBLE Here any string you pass!!
var urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(myString).json"
A simple way of doing it could be:
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variablename + ".json"
You can also do it like this (a little more typesafe):
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variablename).json"
Swift will read \(variablename) into the string automatically and accepts - among all things - integers.
let variable = 123
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_" + variable + ".json"
or
final let urlString = "https://ozsqiqjf.preview.infomaniak.website/empdata_\(variable).json"

How to append an array in URL request type GET in Swift?

I am using Xcode7.3 with Swift2.2.
I want to append an Array in url request.For example my array like
[“jeevan”,”jeejo”]. I want to append this array with key(arrayKey) in url request like must be the following pattern
https://api.com/pre/ws/ch/roo?arrayKey=jeevan%2Cjeejo
How to solve this issue? Please help me
You need to use encode your URL instead of join Array with separator, but if you want to merge Array with URL you can try like this.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator("%2C")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
If you want to encode url encode this way.
let str = ["jeevan","jeejo"]
let join = str.joinWithSeparator(",")
let url = "https://api.com/pre/ws/ch/roo?arrayKey=\(join)"
let encoded = url.stringByAddingPercentEncodingWithAllowedCharacters(.URLFragmentAllowedCharacterSet())
Note : The reason I have used , is because %2C is encode for , you can confirm it here on W3School URL Encoding.
easy solution can be like this
var URIString = ""
for item in array {
URIString +=\(item)%2C
}
after subtract last 3 characters and make URL string
Simple code like this
var array: [String] = ["jeevan","jeejo"]
var myString = ""
for i in 0..<array.count {
myString += array[i]
if (i+1)<array.count { mystring+="%2C" }
}
Can give you result like this:
jeevan%2Cjeejo

Swift Checking if entire word is present in a string [duplicate]

This question already has answers here:
Detect whole word in NSStrings
(4 answers)
Closed 6 years ago.
What I want to do is to check if an entire word is present in a string. Let me give you an example.
let mainString = "this is a my string"
let searchString = "str"
if mainString.containsString(searchString) {
}
Here this condition will be true but I do not want this. I want it to be true when either "this" or "is" or "a" or "my" or "string" is searched in the mainString meaning I want to compare the whole word not the characters within the string. I hope I have elaborated it.
// The following method will return a string without punctuation and non-required stuff characters
Source of information : How to remove special characters from string in Swift 2?
func removeSpecialCharsFromString(mainString) -> String {
let okayChars : Set<Character> =
Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ".characters)
return String(text.characters.filter {okayChars.contains($0) })
}
let stringWithoutSpecialChars = removeSpecialCharsFromString(mainString)
// Source of info : Chris's answer on this page
let components = stringWithoutSpecialChars.componentsSeparatedByString(" ")
for component in components {
print(component)
}
You have to use a Regex like that :
NSString *pattern = #"\\str\\b";
NSRange range = [text rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
The \b at the end of the pattern do what you want, it will match only whole words.
I would recommend splitting your string into components and seeing if a component matches your string. Below is a method that uses components to check if any word matches a given search term.
func isTermInString(term:String, stringToSearch:String) -> Bool {
let components = stringToSearch.componentsSeparatedByString(" ")
for component in components {
if component == term {
return true
}
}
return false
}

How to get substring of String in Swift? [duplicate]

This question already has answers here:
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 7 years ago.
If I want to get a value from the NSString "😃hello World😃", what should I use?
The return value I want is "hello World".
The smileys can be any string. so i need some regexp to this.
There's more than one way to do it.
First: String in Swift 1.2 is bridged to NSString properly so the answer could be : How to get substring of NSString?
Second: This answer will deal with emoticon characters too.
var s = "😃hello World😃"
let index = advance(s.startIndex, 1) // index is a String.Index to the 2nd glyph, “h”
let endIndex = advance(s.startIndex, 12)
let substring=s[index..<endIndex] // here you got "hello World"
if let emojiRange = s[index...s.endIndex].rangeOfString("😃") {
let substring2 = s[index..<emojiRange.startIndex] // here you get "hello World"
}

Resources