How do I search for a range of Strings [duplicate] - swift

This question already has answers here:
Extracting the RGB value from a string
(2 answers)
Closed 4 years ago.
How do I search for a range of Strings,
I want to search userID
But userID may this time is "123",
next time is "zxvcvb",
so i can't use offsetBy
let userID = "12345"
let URL = "http://test/main/?Username=\(userID)#!/index.php"
let firstIndex = URL.index(of: "=")
let secondIndex = URL.index(of: "#")
let range = firstIndex...secondIndex //error

Try this code :
let userID = "jshjdschd"
let url = "http://test/main/?Username=\(userID)#!/index.php"
guard let firstIndex = url.index(of: "="),
let secondIndex = url[firstIndex...].index(of: "#") else{
print("UserId not found")
}
let range = url.index(after: firstIndex)..<secondIndex
let mySubstring = url[range]
print(mySubstring) //jshjdschd

You can use a regex to get the range of the user ID between those two strings:
let userID = "12345"
let pattern = "(?<=Username=)(.*)(?=#!)"
let link = "http://test/main/?Username=\(userID)#!/index.php"
if let range = link.range(of: pattern, options: .regularExpression) {
let id = link[range]
print("id:", id) // "id: 12345\n"
}

Related

How to trim first 3 character from a string in 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...])
}

How to masking textfield in Swift 4? [duplicate]

This question already has answers here:
How to masking the last number in Swift?
(2 answers)
Closed 3 years ago.
I want masking email in textfield.text, but I only get the value in the middle. I want to get the value from the middle to # gmail.com like example below.
ex:
let var = 12345678#gmail.com
output = ****5678#gmail.com
let var = 123456789#gmail.com
output = ****56789#gmail.com
let email = "123456789#gmail.com"
let components = email.components(separatedBy: "#")
let result = hideMidChars(components.first!) + "#" + components.last!
print(result)
output I get: ****5****#gmail.com
my expectations: ****56789#gmail.com
try extending the string protocol and declare a variable which returns an .init(repeating: ,count):
extension StringProtocol {
var masked: String {
return String(repeating: "•", count: Swift.max(0, count - count/2)) + suffix(count/2)
}
}
usage as follows:
let email = "123456789#gmail.com"
print(email.masked) //"••••••••••gmail.com"
if you want a part of the email showing just manipulate the suffix(count - 3) as follows:
return String(repeating: "•", count: Swift.max(0, count - count/2)) + suffix(count/2)
func hide(email: String) -> String {
let parts = email.split(separator: "#")
if parts.count < 2 {
return email
}
let name = parts[0]
let appendix = parts[1]
let lenght = name.count
if lenght == 1 {
return "*#\(appendix)"
}
let semiLenght = lenght / 2
var suffixSemiLenght = semiLenght
if (lenght % 2 == 1) {
suffixSemiLenght += 1
}
let prefix = String(repeating: "*", count: semiLenght)
let lastPart = String(name.suffix(suffixSemiLenght))
let result = "\(prefix)\(lastPart)#\(appendix)"
return result
}
let email = "123456789#gmail.com"
let result = hide(email: email)
print(result)

hide some numbers with star in phone number UIlabel using for otp verification swift 4 app

i am making an app in swift 4 and i want the enetered number label text to show something like this when otp is sent
" otp is sent to +91******21 "
here is the thing I found now I don't own what logic should be applied here to post string like that
var mobileNumer = "+91987654321"
let intLetters = mobileNumer.prefix(3)
let endLetters = mobileNumer.suffix(2)
i want this tpe of number to be shown on the label after enytering the mobile number , it should show frist two numbers then start and hen show last two numbers
try this:
var mobileNumer = "+91987654321"
let intLetters = mobileNumer.prefix(3)
let endLetters = mobileNumer.suffix(2)
let newString = intLetters + "*******" + endLetters //"+91*******21"
Or if you want to be safe:
var mobileNumer = "+91987654321"
guard mobileNumer.count > 5 else {
fatalError("The phone number is not complete")
}
let intLetters = mobileNumer.prefix(3)
let endLetters = mobileNumer.suffix(2)
let stars = String(repeating: "*", count: mobileNumer.count - 5)
let result = intLetters + stars + endLetters
Or if you'd prefer to replace a subrange:
var mobileNumer = "+91987654321"
guard mobileNumer.count > 5 else {
fatalError("The phone number is not complete")
}
let startingIndex = mobileNumer.index(mobileNumer.startIndex, offsetBy: 3)
let endingIndex = mobileNumer.index(mobileNumer.endIndex, offsetBy: -2)
let stars = String(repeating: "*", count: mobileNumer.count - 5)
let result = mobileNumer.replacingCharacters(in: startingIndex..<endingIndex,
with: stars)
Or
If you'd like to mutate mobileNumer:
mobileNumer.replaceSubrange(startingIndex..<endingIndex, with: stars)
print(mobileNumer) //"+91*******21"
You can use this function.
func starifyNumber(number: String) -> String {
let intLetters = number.prefix(3)
let endLetters = number.suffix(2)
let numberOfStars = number.count - (intLetters.count + endLetters.count)
var starString = ""
for _ in 1...numberOfStars {
starString += "*"
}
let finalNumberToShow: String = intLetters + starString + endLetters
return finalNumberToShow
}
To call it
let mobileNumer = starifyNumber(number: "+91987654321")
print(mobileNumer) \\+91*******21

How to succinctly get the first 5 characters of a string in swift?

What is the most succinct way to get the first 5 characters of a String in swift? Thank you.
First 5 chars
let str = "SampleText"
let result = String(str.characters.prefix(5)) // result = "Sampl"
SWIFT 4
let str = "SampleText"
let result = String(str.prefix(5)) // result = "Sampl"
In Swift 4 it changed:
let text = "sampleText"
let resultPrefix = text.prefix(5) //result = "sampl"
let resultSuffix = text.suffix(6) // result = "eText"
Get the index upto 5 character and then use substring
let str = "Hello World!"
if str.utf16.count >= 5{
let a = str.index(str.startIndex, offsetBy: 5)
let result = str.substring(to: a)
}else{
//lenght in shorter
}
In Swift 5,
let str:String = "Sam Fisher"
let result = str.prefix(3) //You get 'sam'

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))
}
}