How to trim first 3 character from a string in swift - swift

I have a dropdown(userCphList) in which there are 2 value : 66/001/0004, 66/002/9765. I want to trim the selected value of dropdown from 66/001/0004 to 001/0004.
Given below is my code:
userCphList.didSelect{(selectedText , index ,id) in
let cphid = selectedText
let url = self.appDelegate.BaseUrl + "geojson/proj_4326?cph_id=" + cphid
self.get_wl_geojsondata(url: url)
}
I want to get cphid as 001/0004.
Any help will be highly appreciated!
Thank You!
Rutuparna Panda

You can split your string where separator is a slash, drop the first component and then join it again:
let str = "66/001/0004"
let trimmed = str.split { $0 == "/" }
.dropFirst()
.joined(separator: "/") // "001/0004"
Another option is to find the first slash index and get the substring after it:
if let index = str.firstIndex(of: "/") {
let trimmed = str[str.index(after: index)...] // "001/0004"
// or simply dropping the first character
// let trimmed = str[index...].dropFirst()
}

If the number of characters to be dropped is fixed the easiest way is dropFirst
let string = "66/001/0004"
let trimmedString = String(string.dropFirst(3))
Other ways are Regular Expression
let trimmedString = string.replacingOccurrences(of: "^\\d+/", with: "", options: .regularExpression)
and removing the substring by range
if let range = string.range(of: "/") {
let trimmedString = String(string[range.upperBound...])
}

Related

How to get specific string after and before specific character in swift?

I have this string: "lat/lng: (-6.2222391,106.7035684)"
I only need to get those double data type in that string. so how to get just only *-6.222239*1 and 106.7035684 as string variable?
How to get the number in that parenthesis?
So I think I have get string after "(" and before "," to get "-6.2222391" and also after "," and before ")" to get "106.7035684"
but I don't know how to get that in code
let source = "lat/lng: (-6.2222391,106.7035684)"
let splited = source.components(separatedBy: "lat/lng: ")[1] //separating
let removed = splited.replacingOccurrences(of: "(", with: "").replacingOccurrences(of: ")", with: "") // removing
let coord = removed.components(separatedBy: ",") // removing
let lat = Double(coord[0])
let lng = Double(coord[1])
You could use a regex:
let str = "lat/lng: (-6.2222391,106.7035684)"
let rg = NSRange(location: 0, length: (str as NSString).length)
let latRegex = try! NSRegularExpression(pattern: "(?<=\\()[+-\\.0-9]+(?=,)")
(?<=\\() is positive lookbehind, it looks for anything preceded by (,
[+-\\.0-9]+ eagerly looks for at least one character or more that are either +, -, ., or a digit from 0 to 9,
(?=,) is positive lookahead, it matches anything followed by ,.
Now let's use this regular expression :
let latitude: Double? = latRegex.matches(in: str, range: rg)
.compactMap { Double(str[Range($0.range, in: str)!]) }
.first
if let lat = latitude {
print(lat) //-6.2222391
}
In the same way, we can get the longitude :
let longRegex = try! NSRegularExpression(pattern: "(?<=,)[+-\\.0-9]+(?=\\))")
let longitude: Double? = longRegex.matches(in: str, range: rg)
.compactMap { Double(str[Range($0.range, in: str)!]) }
.first
if let long = longitude {
print(long) //106.7035684
}
PS: I've used forced unwrapping here and there for brevity
You have received some good answers already. But I think I've come up with a more compact version.
You need to care about - 0~9 . and ,
The , will be considered only for having the two components and then be used for separating them.
See this:
let source = "lat/lng: (-6.2222391,106.7035684)"
let allowedCharactersString = "-01234567890.,"
let latLongValues = String(source.characters.filter {
allowedCharactersString.characters.contains($0)
}).components(separatedBy: ",")
print(latLongValues.first!) // "-6.2222391"
print(latLongValues.last!) // "106.7035684"
Try this:
let source = "lat/lng: (-6.2222391,106.7035684)".components(separatedBy: ")")[0]
let removed = source.components(separatedBy: "(")[1];// removing
//OR
//let source = "lat/lng: (-6.2222391,106.7035684)".components(separatedBy: "(")[1]
//let removed = source.components(separatedBy: ")")[0];// removing
let coord = removed.components(separatedBy: ",") // removing
let lat = Double(coord[0])
let lng = Double(coord[1])

How to filter non-digits from string

My phone numbers are like +7 (777) 777-7777.
I need only digits and plus symbol: +77777777777 to make calls.
This returns only digits:
let stringArray = origString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = NSArray(array: stringArray).componentsJoinedByString("")
One of the many ways to do that:
let isValidCharacter: (Character) -> Bool = {
($0 >= "0" && $0 <= "9") || $0 == "+"
}
let newString = String(origString.characters.filter(isValidCharacter))
or using a regular expression:
// not a +, not a number
let pattern = "[^+0-9]"
// replace anything that is not a + and not a number with an empty string
let newString = origString.replacingOccurrences(
of: pattern,
with: "",
options: .regularExpression
)
or, if you really want to use your original solution with a character set.
let validCharacters = CharacterSet(charactersIn: "0123456789+")
let newString = origString
.components(separatedBy: validCharacters.inverted)
.joined()
In keeping with the spirit of your partial solution,
let origString:NSString = "+7 (777) 777-7777"
let cs = NSCharacterSet(charactersIn: "0123456789+")
let final = origString.components(separatedBy: cs.inverted).joined()

Find characters inside quotation marks in String

I'm trying to pull out the parts of a string that are in quotation marks, i.e. in "Rouge One" is an awesome movie I want to extract Rouge One.
This is what I have so far but can't figure out where to go from here: I create a copy of the text so that I can remove the first quotation mark so that I can get the index of the second.
if text.contains("\"") {
guard let firstQuoteMarkIndex = text.range(of: "\"") else {return}
var textCopy = text
let textWithoutFirstQuoteMark = textCopy.replacingCharacters(in: firstQuoteMarkIndex, with: "")
let secondQuoteMarkIndex = textCopy.range(of: "\"")
let stringBetweenQuotes = text.substring(with: Range(start: firstQuoteMarkIndex, end: secondQuoteMarkIndex))
}
There is no need to create copies or to replace substrings for this task.
Here is a possible approach:
Use text.range(of: "\"") to find the first quotation mark.
Use text.range(of: "\"", range:...) to find the second quotation mark, i.e. the first one after the range found in step 1.
Extract the substring between the two ranges.
Example:
let text = " \"Rouge One\" is an awesome movie"
if let r1 = text.range(of: "\""),
let r2 = text.range(of: "\"", range: r1.upperBound..<text.endIndex) {
let stringBetweenQuotes = text.substring(with: r1.upperBound..<r2.lowerBound)
print(stringBetweenQuotes) // "Rouge One"
}
Another option is a regular expression search with "positive lookbehind" and "positive lookahead" patterns:
if let range = text.range(of: "(?<=\\\").*?(?=\\\")", options: .regularExpression) {
let stringBetweenQuotes = text.substring(with: range)
print(stringBetweenQuotes)
}
var rouge = "\"Rouge One\" is an awesome movie"
var separated = rouge.components(separatedBy: "\"") // ["", "Rouge One", " is an awesome movie"]
separated.dropFirst().first
I would use .components(separatedBy:)
let stringArray = text.components(separatedBy: "\"")
Check if stringArray count is > 2 (there is at least 2 quotes).
Check if stringArray count is odd, aka count % 2 == 1.
If it is odd, all the even indices are between 2 quotes and they are what you want.
If it is even, all the even indices - 1 are between 2 quotes (the last one doesn't have an end quote).
This will allow you to also capture multiple sets of quoted strings, like:
"Rogue One" is a "Star Wars" movie.
Another option is to use regular expressions to find pairs of quotes:
let pattern = try! NSRegularExpression(pattern: "\\\"([^\"]+)\\\"")
// Small helper methods making it easier to work with enumerateMatches(in:...)
extension String {
subscript(utf16Range range: Range<Int>) -> String? {
get {
let start = utf16.index(utf16.startIndex, offsetBy: range.lowerBound)
let end = utf16.index(utf16.startIndex, offsetBy: range.upperBound)
return String(utf16[start..<end])
}
}
var fullUTF16Range: NSRange {
return NSRange(location: 0, length: utf16.count)
}
}
// Loop through *all* quoted substrings in the original string.
let str = "\"Rogue One\" is an awesome movie"
pattern.enumerateMatches(in: str, range: str.fullUTF16Range) { (result, flags, stop) in
// rangeAt(1) is the range representing the characters in the 1st
// capture group of the regular expression: ([^"]+)
if let result = result, let range = result.rangeAt(1).toRange() {
print("This was in quotes: \(str[utf16Range: range] ?? "<bad range>")")
}
}

How to get the first characters in a string? (Swift 3)

I want to get a substring out of a string which starts with either "<ONLINE>" or "<OFFLINE>" (which should become my substring). When I try to create a Range object, I can easily access the the first character by using startIndex but how do I get the index of the closing bracket of my substring which will be either the 8th or 9th character of the full string?
UPDATE:
A simple example:
let onlineString:String = "<ONLINE> Message with online tag!"
let substring:String = // Get the "<ONLINE> " part from my string?
let onlineStringWithoutTag:String = onlineString.replaceOccurances(of: substring, with: "")
// What I should get as the result: "Message with online tag!"
So basically, the question is: what do I do for substring?
let name = "Ajay"
// Use following line to extract first chracter(In String format)
print(name.characters.first?.description ?? "");
// Output : "A"
If you did not want to use range
let onlineString:String = "<ONLINE> Message with online tag!"
let substring:String = onlineString.components(separatedBy: " ")[0]
print(substring) // <ONLINE>
The correct way would be to use indexes as following:
let string = "123 456"
let firstCharIndex = string.index(string.startIndex, offsetBy: 1)
let firstChar = string.substring(to: firstCharIndex)
print(firstChar)
This Code provides you the first character of the string.
Swift provides this method which returns character? you have to wrap it before use
let str = "FirstCharacter"
print(str.first!)
Similar to OOPer's:
let string = "<ONLINE>"
let closingTag = CharacterSet(charactersIn: ">")
if let closingTagIndex = string.rangeOfCharacter(from: closingTag) {
let mySubstring = string.substring(with: string.startIndex..<closingTagIndex.upperBound)
}
Or with regex:
let string = "<ONLINE>jhkjhkh>"
if let range = string.range(of: "<[A-Z]+>", options: .regularExpression) {
let mySubstring = string.substring(with: range)
}
This code be some help for your purpose:
let myString = "<ONLINE>abc"
if let rangeOfClosingAngleBracket = myString.range(of: ">") {
let substring = myString.substring(to: rangeOfClosingAngleBracket.upperBound)
print(substring) //-><ONLINE>
}
Swift 4
let firstCharIndex = oneGivenName.index(oneGivenName.startIndex, offsetBy: 1)
let firstChar = String(oneGivenName[..<firstCharIndex])
let character = MyString.first
it's an simple way to get first character from string in swift.
In swift 5
let someString = "Stackoverflow"
let firstChar = someString.first?.description ?? ""
print(firstChar)
Swift 5 extension
extension String {
var firstCharactor: String? {
guard self.count > 0 else {
return nil
}
return String(self.prefix(1))
}
}

How to remove slash "/" in string in Swift

I have a string like "http://example.com/a/b/c". I want to transform the string to "httpexamplecomabc" in order to save it as the file name. I have tried
let result = str.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "//"))
and
let result = str.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "/"))
but neither works. Any Idea on how to remove "/"? Thanks
You can replace occurrence of "/ " to "" by using
let mm = "http://example.com/a/b/c"
let newString = mm.stringByReplacingOccurrencesOfString("/", withString: "")
print(newString) // http:example.comabc