How can I remove character in specific range [duplicate] - swift

This question already has an answer here:
Understanding the removeRange(_:) documentation
(1 answer)
Closed 2 years ago.
how can i remove character from string with rang. for example «banana» i want to remove only a from index (1..<3), i don’t want to remove the first and last character if they where «a»
i want from banana to bnna only removed the two midle.
the only thing i can do now is to remove the all “a”.
var charr = "a"
var somfruit = "banana"
var newString = ""
for i in somfruit{
if charr.contains(i) {
continue
}
newString.append(i)
}
print(newString)

In SWIFT 5 try:
var charr = "a"
var somfruit = "banana"
var newString = ""
let lower = somfruit.firstIndex(of: charr) + 1
let upper = somfruit.lastIndex(of: charr) - 1
newString = somfruit.replacingOccurrences(of: charr, with: '', option: nil, range: Range(lower, upper)
print(newString)
This is simplified. firstIndex and lastIndex returns Int? so you have to check they exist and they are not equals.

Related

Issue in removing spaces from string in swift [duplicate]

This question already has answers here:
How should I remove all the leading spaces from a string? - swift
(31 answers)
Closed 4 years ago.
i'm getting my contacts number locally from my mobile. There are some number in which there are white spaces between numbers. I'm trying to remove the white spaces from the number but it isn't working,this is how i'm removing the white spaces,
let number = contact.phoneNumbers.first?.value.stringValue
let formattedString = number?.replacingOccurrences(of: " ", with: "")
print(formattedString)
But when i print this is what i got in the console,
+92 324 4544783
The white sapces are still coming how can i remove that?
Here you go: source
For trimming white spaces from both ends, you can use:
let number = contact.phoneNumbers.first?.value.stringValue
let formattedString = number.trimmingCharacters(in: .whitespacesAndNewlines)
print(formattedString)
For removing whitespaces that might be inside the string, use:
let x = "+92 300 7681277"
let result = x.replacingOccurrences(of: " ", with: "")
You should get:
result = +923007681277
EDIT: I updated my answer.
let number = contact.phoneNumbers.first?.value.stringValue
let number_without_space = number.components(separatedBy: .whitespaces).joined()
print(number_without_space) //use this variable wherever you want to use
joined() is a function it will join your string after removing spaces like this
let str = "String Name"
str.components(separatedBy: .whitespaces).joined()
extension to remove spaces
extension String
{
func removeSpaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
}

How do you split a string at every n-th character in Swift? [duplicate]

This question already has answers here:
How to split a string into substrings of equal length
(13 answers)
Closed 4 years ago.
Like the question says, if I have:
XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28
How can I split this string at every 8th character to get:
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSA
Implement this function
extension String {
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: n).forEach {
result += String(characters[$0..<min($0+n, characters.count)])
if $0+n < characters.count {
result += separator
}
}
return result
}
}
call it this way,
let str = "XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28"
let final = str.inserting(separator: " ", every: 8)
print(final)
Output will be like this,
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSF E28
This will be generic solution if you want to add any character instead of space, it will work.

Efficient way to find all instances of Substring within a Swift String [duplicate]

This question already has answers here:
Swift find all occurrences of a substring
(7 answers)
Closed 5 years ago.
Swift 4 apparently has introduced a lot of new changes to String. I'm wondering if there is now a built-in method for finding all instances of a substring within a String.
Here's the kind of thing I'm looking for:
let searchSentence = "hello world, hello"
let wordToMatch = "hello"
let matchingIndexArray = searchSentence.indices(of: "wordToMatch")
'matchingIndexArray' would then be [0, 13]
import Foundation
let searchSentence = "hello world, hello"
var searchRange = searchSentence.startIndex..<searchSentence.endIndex
var ranges: [Range<String.Index>] = []
let searchTerm = "hello"
while let range = searchSentence.range(of: searchTerm, range: searchRange) {
ranges.append(range)
searchRange = range.upperBound..<searchRange.upperBound
}
print(ranges.map { "(\(searchSentence.distance(from: searchSentence.startIndex, to: $0.lowerBound)), \(searchSentence.distance(from: searchSentence.startIndex, to: $0.upperBound)))" })
outputs:
["(0, 5)", "(13, 18)"]

Expeceted Declaration when using for loop [duplicate]

This question already has an answer here:
Expected Declaration Error using Swift
(1 answer)
Closed 5 years ago.
Im just trying to use a for loop to run through some code, but I get an Expected declaration error.
var index = 0
for( i in 0..< array.count) {
let commonPrefix = array[i].commonPrefixWithString(array[index], options: .CaseInsensitiveSearch)
if (countElements(commonPrefix) == 0 ) {
let string = array[index].uppercased();
let firstCharacter = string[string.startIndex]
let title = "\(firstCharacter)"
let newSection = (index: index, length: i - index, title: title)
sections.append(newSection)
index = i
}
}
Help
That's not how you write a for loop in Swift. What you want is this
for i in 0..<array.count {
// the loop inner body
}

How to append a character to a string in Swift?

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.
for aCharacter: Character in aString {
var str: String = ""
var newStr: String = str.append(aCharacter) // ERROR
...
}
Error: Cannot invoke append with an argument of type Character
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]
This also works
var newStr:String = str + String(aCharacter)
append append(c: Character) IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
According to Swift 4 Documentation ,
You can append a Character value to a String variable with the String type’s append() method:
var welcome = "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
var stringName: String = "samontro"
var characterNameLast: Character = "n"
stringName += String(characterNameLast) // You get your name "samontron"
I had to get initials from first and last names, and join them together. Using bits and pieces of the above answers, this worked for me:
var initial: String = ""
if !givenName.isEmpty {
let char = (givenName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
if !familyName.isEmpty {
let char = (familyName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
for those looking for swift 5, you can do interpolation.
var content = "some random string"
content = "\(content)!!"
print(content) // Output: some random string!!
let original:String = "Hello"
var firstCha = original[original.startIndex...original.startIndex]
var str = "123456789"
let x = (str as NSString).substringWithRange(NSMakeRange(0, 4))
var appendString1 = "\(firstCha)\(x)" as String!
// final name
var namestr = "yogesh"
var appendString2 = "\(namestr) (\(appendString1))" as String!*