Delete all character after particular character in string - ios

I have a string and I want to delete some character after particulate character, I tried using with substring but nothings working

"word" is a String Variable here where you can apply your needs and "T" is a character after which you want to delete all other characters
if let index = word.range(of: "T")?.lowerBound {
let substring = word[..<index]
let string = String(substring)
self.birthdayField.text = string
}

Related

Swift: Get an index of beginning and ending character of a word in a String

A string:
"jim#domain.com, bill#domain.com, chad#domain.com, tom#domain.com"
Through gesture recognizer, I am able to get the character the user tapped on (happy to provide code, but don't see the relevance at this point).
Let's say the User tapped on o in "chad#domain.com" and the character index is 39
Given 39 the index of o, I would like to get the string start index of c where "chad#domain.com" begins, and an end index for m from "com" where "chad#domain.com" ends.
In another words, given an index of a character in a String, I need to get the index on the left and right right before we encounter a space in a String on the left and a comma on the right.
Tried, but this only provides the last word in the String:
if let range = text.range(of: " ", options: .backwards) {
let suffix = String(text.suffix(from: range.upperBound))
print(suffix) // tom#domain.com
}
I am not sure where to go from here?
You can call range(of:) on two slices of the given string:
text[..<index] is the text preceding the given character position,
and text[index...] is the text starting at the given position.
Example:
let text = "jim#domain.com, bill#domain.com, chad#domain.com, tom#domain.com"
let index = text.index(text.startIndex, offsetBy: 39)
// Search the space before the given position:
let start = text[..<index].range(of: " ", options: .backwards)?.upperBound ?? text.startIndex
// Search the comma after the given position:
let end = text[index...].range(of: ",")?.lowerBound ?? text.endIndex
print(text[start..<end]) // chad#domain.com
Both range(of:) calls return nil if no space (or comma) has
been found. In that case the nil-coalescing operator ?? is used
to get the start (or end) index instead.
(Note that this works because Substrings share a common index
with their originating string.)
An alternative approach is to use a "data detector",
so that the URL detection does not depend on certain separators.
Example (compare How to detect a URL in a String using NSDataDetector):
let text = "jim#domain.com, bill#domain.com, chad#domain.com, tom#domain.com"
let index = text.index(text.startIndex, offsetBy: 39)
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: text, range: NSRange(location: 0, length: text.utf16.count))
for match in matches {
if let range = Range(match.range, in: text), range.contains(index) {
print(text[range])
}
}
Different approach:
You have the string and the Int index
let string = "jim#domain.com, bill#domain.com, chad#domain.com, tom#domain.com"
let characterIndex = 39
Get the String.Index from the Int
let stringIndex = string.index(string.startIndex, offsetBy: characterIndex)
Convert the string into an array of addresses
let addresses = string.components(separatedBy: ", ")
Map the addresses to their ranges (Range<String.Index>) in the string
let ranges = addresses.map{string.range(of: $0)!}
Get the (Int) index of the range which contains stringIndex
if let index = ranges.index(where: {$0.contains(stringIndex)}) {
Get the corresponding address
let address = addresses[index] }
One approach could be to split the original string on the “,” and then using simple math to find in what element of the array the given position (39) exist and from there get the right string or indexes for the previous space and next comma depending on what your end goal is.

Cut a String from start position to end position with swift 3

I have Strings with the form string \ string example
"some sting with random length\233"
I want to deletes the last \ and get the value after it, so the result will be
"some sting with random length"
"233"
I tried this code but it's not working
let regex = try! NSRegularExpression(pattern: "\\\s*(\\S[^,]*)$")
if let match = regex.firstMatch(in: string, range: string.nsRange) {
let result = string.substring(with: match.rangeAt(1))
}
You did not correctly adapt the pattern from How to get substring after last occurrence of character in string: Swift IOS to your case. Both instances of the comma must be replaced by a backslash,
and that must be "double-escaped":
let regex = try! NSRegularExpression(pattern: "\\\\\\s*(\\S[^\\\\]*)$")
(once be interpreted as a literal backslash in the regex pattern, and
once more in the definition of a Swift string literal).
However, a simpler solution is to find the last occurrence of the
backslash and extract the suffix from that position:
let string = "some sting with random length\\233"
let separator = "\\" // A single(!) backslash
if let r = string.range(of: separator, options: .backwards) {
let prefix = string.substring(to: r.lowerBound)
let suffix = string.substring(from: r.upperBound)
print(prefix) // some sting with random length
print(suffix) // 233
}
Update for Swift 4:
if let r = string.range(of: separator, options: .backwards) {
let prefix = string[..<r.lowerBound]
let suffix = string[r.upperBound...]
print(prefix) // some sting with random length
print(suffix) // 233
}
prefix and suffix are a String.SubSequence, which can be used
in many places instead of a String. If necessary, create a real
string:
let prefix = String(string[..<r.lowerBound])
let suffix = String(string[r.upperBound...])
You could do this with regex, but I think this solution is better:
yourString.components(separatedBy: "\\").last!
It splits the string with \ as the separator and gets the last split.

How to get frequency of line feed in string by swift

Sorry,I'm new of swift. I want to calculate the target char in string.But I don't know how to do.Have any good suggestion to me?Thanks.
let string = "hello\nNice to meet you.\nMy name is Leo.\n" //I want to get 3
If you simply want a count of newline characters then you can use a filter on the string's characters:
let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let count = string.characters.filter { $0 == "\n" }.count
print(count)
This outputs 3 as expected.
An alternative is to split the lines with the components(separatedBy method:
let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let lineCounter = string.components(separatedBy: "\n").count - 1
or more versatile to consider all kinds of newline characters
let lineCounter = string.components(separatedBy: CharacterSet.newlines).count - 1
Due to the trailing newline character the result is 4. To ignore a trailing new line you have to decrement the result.

How to capitalize each alternate character of a string?

Lets say there is a string "johngoestoschool" it should become "JoHnGoEsToScHoOl" and incase if there is a special character in between it should ignore it for example given string "jo$%##hn^goe!st#os&choo)l" answer should be "Jo$%##Hn^GoE!sT#oS&cHoO)l"
From this answer, we in order to iterate we can do:
let s = "alpha"
for i in s.characters.indices[s.startIndex..<s.endIndex]
{
print(s[i])
}
Why can't we print the value of "i" here?
When we do i.customPlaygroundQuickLook it types int 0 to int4.
So my idea is to
if (i.customPlaygroundQuickLook == 3) {
s.characters.currentindex = capitalized
}
Kindly help
This should solve your function, the hard part is just checking weather the character is letters or not, using inout and replace range would give better performance:
func altCaptalized(string: String) -> String {
var stringAr = string.characters.map({ String($0) }) // Convert string to characters array and mapped it to become array of single letter strings
var numOfLetters = 0
// Convert string to array of unicode scalar character to compare in CharacterSet
for (i,uni) in string.unicodeScalars.enumerated() {
//Check if the scalar character is in letter character set
if CharacterSet.letters.contains(uni) {
if numOfLetters % 2 == 0 {
stringAr[i] = stringAr[i].uppercased() //Replace lowercased letter with uppercased
}
numOfLetters += 1
}
}
return stringAr.joined() //Combine all the single letter strings in the array into one string
}

How to use rangeOfString below in Swift

Suppose I have a string "10.9.1.1", I want to get substring "10.9". How can I achieve this?
So far I have the following:
var str = "10.9.1.1"
let range = str.rangeOfString(".",options: .RegularExpressionSearch)!
let rangeOfDecimal = Range(start:str.startIndex,end:range.endIndex)
var subStr = str.subStringWithRange(rangeOfDecimal)
But this will only return 10.
Actually your code returns "1" only, because "." in a regular
expression pattern matches any character.
The correct pattern would be
\d+ one ore more digits
\. a literal dot
\d+ one or more digits
In a Swift string, you have to escape the backslashes as "\\":
let str = "10.9.1.1"
if let range = str.rangeOfString("\\d+\\.\\d+",options: .RegularExpressionSearch) {
let subStr = str.substringWithRange(range)
println(subStr) // "10.9"
}

Resources