iOS Swift manipulate/parse string - ios

I'm not sure how to do this in iOS Swift
let test = "fnfsjflsjlkdkfj?v=904kg4"
// search test for ?v= and store everything after ?v= into a new string
let newString = "904kg4"
I want everything after ?v= into a new string, is this possible? if so, how can I accomplish this

Use rangeOfString to find the range of ?v= and then use substringFromIndex to get the rest of the string:
let test = "fnfsjflsjlkdkfj?v=904kg4"
if let range = test.rangeOfString("?v=") {
let newString = test.substringFromIndex(range.endIndex)
}

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

Value of type 'String' has no member 'substringToIndex' not resolved

I am trying to grab currentLanguage of a device using the below function. But there has been an issue with substring and I don't seem to understand as previous answers have such simple solution of importing Foundation to the file, which didn't work for me.
class func currentLanguage() -> String
{
let str = "en-US"
if let indexOfDash = str.characters.index(of: "-")
{
let langCode = str.substringToIndex(indexOfDash)
return langCode
}
}
In addition, What can be the best approach to get current language?
You need to use
let langCode = str.substring(to: indexOfDash)
And you can get current language like that:
let pre = NSLocale.preferredLanguages[0]

How to take NSRange in swift?

I am very much new to swift language. I am performing some business logic which needs to take NSRange from given String.
Here is my requirement,
Given Amount = "144.44"
Need NSRange of only cent part i.e. after "."
Is there any API available for doing this?
You can do a regex-based search to find the range:
let str : NSString = "123.45"
let rng : NSRange = str.range("(?<=[.])\\d*$", options: .RegularExpressionSearch)
Regular expression "(?<=[.])\\d*$" means "zero or more digits following a dot character '.' via look-behind, all the way to the end of the string $."
If you want a substring from a given string you can use componentsSeparatedByString
Example :
var number: String = "144.44";
var numberresult= number.componentsSeparatedByString(".")
then you can get components as :
var num1: String = numberresult [0]
var num2: String = numberresult [1]
hope it help !!
Use rangeOfString and substringFromIndex:
let string = "123.45"
if let index = string.rangeOfString(".") {
let cents = string.substringFromIndex(index.endIndex)
print("\(cents)")
}
Another version that uses Swift Ranges, rather than NSRange
Define the function that returns an optional Range:
func centsRangeFromString(str: String) -> Range<String.Index>? {
let characters = str.characters
guard let dotIndex = characters.indexOf(".") else { return nil }
return Range(dotIndex.successor() ..< characters.endIndex)
}
Which you can test with:
let r = centsRangeFromString(str)
// I don't recommend force unwrapping here, but this is just an example.
let cents = str.substringWithRange(r!)

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

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)

how to split a string like char and number separately in swift

i am facing one issue about how to split a number and string in same String and display it. To be very clear lets take an example i have an string like,
myString = "MH04ED7897"
i want to my output like this
outPut = MH-04-ED-7897
I am new in Swift. try this
let startIndex = number.startIndex.advancedBy(4)
let lastStr:String = number.substringFromIndex(startIndex)
let InitialStr:String = number.substringToIndex(startIndex)
NSLog("%# %#", lastStr,InitialStr)
let startInitialIndex = InitialStr.startIndex.advancedBy(2)
let InitialStart:String = InitialStr.substringToIndex(startInitialIndex)
let Initialfinish:String = InitialStr.substringFromIndex(startInitialIndex)
print("initalStart :\(InitialStart)")
print("Initialfinish :\(Initialfinish)")
let startlastIndex = lastStr.endIndex.advancedBy(-4)
let lastStart:String = lastStr.substringFromIndex(startlastIndex)
let replaced = lastStr.stringByReplacingOccurrencesOfString(lastStart, withString: "")
print("replace:\(replaced)")
// let lastFinish:String = lastStr.substringToIndex(startfirstIndex)
print("lastStart :\(lastStart)")
you get output like

Resources