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

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.

Related

How can I remove character in specific range [duplicate]

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.

Extracting value with backlash from string value swift [duplicate]

This question already has answers here:
regex to get string between two % characters
(2 answers)
Closed 2 years ago.
Hi am trying to get values of a string which is imputed in the form "40|LQ,FP,MD,GR \"Dinner out\"". The string value I am trying to extract is Dinner out the text could be different though like ride in but it still follows the same pattern. how can I extract this string value from the rest of the character using regex of any alternative.
You can try
var text = "40|LQ,FP,MD,GR \"Dinner out\""
var regex = try? NSRegularExpression(pattern: "\\\".+?\\\"", options: [])
var matches = regex?.matches(in: text, options: []
, range: NSMakeRange(0, text.count)) ?? []
for match in matches {
let r = (text as NSString).substring(with: match.range)
print("found= \(r)")
}
I would recommend you to have a look at this question and its answers.
Swift Get string between 2 strings in a string
Quoting answer here just for your ease.
extension String {
func slice(from: String, to: String) -> String? {
return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
String(self[substringFrom..<substringTo])
}
}
}
}

Swift – How to find out if a string contains several identical characters? [duplicate]

This question already has answers here:
Number of occurrences of substring in string in Swift
(12 answers)
how to count specific items in array in swift
(3 answers)
Closed 3 years ago.
Here's a simple code that let us find out if a string contains a dot characters (we don't know how many, we just know that it contains it):
var number: String = "3.14"
if number.contains(".") {
print("The string contains a dot character")
} else {
print("There's no dot character")
}
But imagine a situation where user wrongly puts 2 or 3 dots in a line, like this:
var number: String = "3...14"
How to check whether a string contains one dot or several ones?
How to count all the dots in the string?
You can use filter(_:) on the string and count to get the number of dots:
let str = "3..14"
switch str.filter({ $0 == "." }).count {
case 0:
print("string has no dots")
case 1:
print("string has 1 dot")
default:
print("string has 2 or more dots")
}

How to split or iterate over an Int without converting to String in Swift [duplicate]

This question already has answers here:
Break A Number Up To An Array of Individual Digits
(6 answers)
Closed 5 years ago.
I was wondering if there was a way in Swift to split an Int up into it's individual digits without converting it to a String. For example:
let x: Int = 12345
//Some way to loop/iterate over x's digits
//Then map each digit in x to it's String value
//Return "12345"
For a bit of background, I'm attempting to create my own method of converting an Int to a String without using the String description property or using String Interpolation.
I've found various articles on this site but all the ones I've been able to find either start with a String or end up using the String description property to convert the Int to a String.
Thanks.
Just keep dividing by 10 and take the remainder:
extension Int {
func digits() -> [Int] {
var digits: [Int] = []
var num = self
repeat {
digits.append(num % 10)
num /= 10
} while num != 0
return digits.reversed()
}
}
x.digits() // [1,2,3,4,5]
Note that this will return all negative digits if the value is negative. You could add a special case if you want to handle that differently. This return [0] for 0, which is probably what you want.
And because everyone like pure functional programming, you can do it that way too:
func digits() -> [Int] {
let partials = sequence(first: self) {
let p = $0 / 10
guard p != 0 else { return nil }
return p
}
return partials.reversed().map { $0 % 10 }
}
(But I'd probably just use the loop here. I find sequence too tricky to reason about in most cases.)
A recursive way...
extension Int {
func createDigitArray() -> [Int] {
if self < 10 {
return [self]
} else {
return (self / 10).createDigitArray() + [self % 10]
}
}
}
12345.createDigitArray() //->[1, 2, 3, 4, 5]
A very easy approach would be using this function:
func getDigits(of number: Int) -> [Int] {
var digits = [Int]()
var x = number
repeat{
digits.insert(abs(x % 10), at: 0)
x/=10
} while x != 0
return digits
}
And using it like this:
getDigits(of: 97531) // [9,7,5,3,1]
getDigits(of: -97531) // [9,7,5,3,1]
As you can see, for a negative number you will receive the array of its digits, but at their absolute value (e.g.: -9 => 9 and -99982 => 99982)
Hope it helps!

Why does my string cleanup function return the original value? [duplicate]

This question already has an answer here:
Can't replacing string with string
(1 answer)
Closed 7 years ago.
I have made a func so that I easily can make all letters of a string lower case, while also removing all ! and spaces. I made this func (outside of viewdidload)
func cleanLink(linkName: String) -> String {
linkName.stringByReplacingOccurrencesOfString("!", withString: "")
linkName.stringByReplacingOccurrencesOfString(" ", withString: "")
linkName.lowercaseString
return linkName
}
I then used these lines of codes
var theLinkName = cleanLink("AB C!")
print(theLinkName)
The problems is that this is just printing AB C! while I want it to print abc. What am I doing wrong?
The problem is that stringByReplacingOccurrencesOfString returns a new string; it does not perform the replacement in place.
You need to use the return value of the function instead, like this:
func cleanLink(linkName: String) -> String {
return linkName
.stringByReplacingOccurrencesOfString("!", withString: "")
.stringByReplacingOccurrencesOfString(" ", withString: "")
.lowercaseString
}
This "chains" the invocations of functions that produce new strings, and returns the final result of the replacement.