Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I have a String, lets say
var abc : String = "aaaabbbbbbbccddd"
I need an algorithm on how to change these repeating letters to the number of repeating letters (if there is more than 2 in a row), so that the given string would become
abc = "a4b7ccd3"
Any hint would be appreciated.
Let's start with this string :
let abc : String = "aaaabbbbbbbccddde"
And have the output in a new variable
var result = ""
Let's use an index to go through the characters in the string
var index = abc.startIndex
while index < abc.endIndex {
//There is already one character :
let char = abc[index]
var count = 0
//Let's check the following characters, if any
repeat {
count += 1
index = abc.index(after: index)
} while index < abc.endIndex && abc[index] == char
//and update the result accordingly
result += count < 3 ?
String(repeating: char, count: count) :
String(char) + String(count)
}
And here is the result :
print(result) //a4b7ccd3e
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I face the problem. When i try to reverse only letters in swift by using Two pointer pattern its actually doing swap instead.
sample - Test 123 String
2 pointer output - gnir 123 tStseT
expected output - tseT 123 gnirtS
Can somebody advice the method, or give example of code pls.?
func reverseOnlyLetters(_ S: String) -> String {
var a = Array(S.unicodeScalars)
var i = 0
var j = a.count - 1
while i < j {
while !CharacterSet.letters.contains(a[i]) && i < j { i += 1 }
while !CharacterSet.letters.contains(a[j]) && i < j { j -= 1 }
let t = a[i]
a[i] = a[j]
a[j] = t
i += 1
j -= 1
}
var ret = ""
a.forEach({ ret += String(Character(UnicodeScalar($0))) })
return ret
}
try this:
func reverseOnlyLetters(_ S: String) -> String {
let components = S.components(separatedBy: " ")
let reversedComponents = components.map { Int($0) == nil ? String($0.reversed()) : $0 }
return reversedComponents.joined(separator: " ")
}
if it still not correct, please give me more infomation
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have some variables all coming true just tarih1 output shows
Optional(2016). I didn't resolve it. I want to fix it to 2016.
My code below.
if let myString: String = String(seans.SeanceDate) {
let myStringArrf = myString.componentsSeparatedByString("T")
let tarih: NSString = myStringArrf[0]
let saat: String = String(myStringArrf[1])
let myStringArrf2 = saat.componentsSeparatedByString(":")
let saat1: String = myStringArrf2[0]
let saat2: String = myStringArrf2[1]
cell.saat.text = "\(saat1):\(saat2)"
cell.saat2.text = "\(saat1):\(saat2)"
let myStringArrf23 = tarih.componentsSeparatedByString("-")
let tarih1: NSString = myStringArrf23[0]
let tarih2: NSString = myStringArrf23[1]
let tarih3: NSString = myStringArrf23[2]
let sontarih: String = ("\(tarih3)-\(tarih2)-\(tarih1)")
cell.tarih.text = sontarih
print(sontarih)
}
You use optional binding to find out whether an optional contains a value, and if so, to make that
value available as a temporary constant or variable. Optional binding can be used with if and while
statements to check for a value inside an optional, and to extract that value into a constant or variable,
as part of a single action
if let constantName = someOptional {
// statements
}
if let tarih1 = myStringArrf23[0]{
print(tarih1)
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
punch in # 2:00:00 and pushed out at 4:15:20, and the time calculation came out right.. Time = 2:15:20 I want to be able to multiply this with 10.50, and I'm unable to convert time to decimal so I can easily multiply it.
I've done a lots of conversations but none of them made any sense and need help...
would you please help thanks.
Try like this:
let startString = "2:00:00"
let endString = "4:15:20"
func secondsFromMidnight(input:String) -> Int {
let comps = input.componentsSeparatedByString(":")
let h = (Int(comps.first!) ?? 0) * 3600
let m = (Int(comps[1]) ?? 0) * 60
let s = Int(comps.last!) ?? 0
return h + m + s
}
let start = secondsFromMidnight(startString)
let end = secondsFromMidnight(endString)
let elapsedTime = Double( end - start )
let dateComponentsFormatter = NSDateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [.Hour,.Minute,.Second]
dateComponentsFormatter.stringFromTimeInterval(elapsedTime) // "2:15:20"
let result = elapsedTime * 10.5
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying match String patterns in Swift. In my case related to time,
Example
"in 1 week"
"in 4 weeks"
I want to match the whole expression but return especially the number (Int) used between "in" and "week".
What's an efficient way to do this kind of string/pattern matching?
I did use e.g. rangeOfString for simple string matching before but I wonder how to tackle matching these more complex string patterns including its variable part.
Try this:
var pattern = "in\\s+(\\d+)\\s+weeks"
var error: NSError?
var regExp = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!
func getWeekCount(input: String) -> String? {
let m = regExp.matchesInString(input, options: nil, range:NSMakeRange(0, countElements(input)))
print(m)
if let mm = m as? [NSTextCheckingResult] {
print(mm.count)
if mm.count >= 1 {
let range = m[0].rangeAtIndex(1)
return NSString(string: input).substringWithRange(range)
}
}
else {
print("no match")
}
return nil
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my string:
(
"2|Apples / amount",
"5|Pizza / pieces",
"10|Oranges / amount",
"1|Brownie / piece"
)
How to get the number, name of the food and unit of the food in arrays
var number:NSMutableArray = NSMutableArray()
var foodName:NSMutableArray = NSMutableArray()
var foodUnit:NSMutableArray = NSMutableArray()
You will need to Split a string into an array.
Not tested but this is the gist of it:
let myFood = ["2|Apples / amount", "5|Pizza / pieces", "10|Oranges / amount", "1|Brownie / piece"]
foreach value in myFood {
let numberAndInfo = myFood.componentsSeparatedByString("|")
// Insert numberAndInfo[0] in your number array.
let foodAndAmount = numberAndInfo[1].componentsSeparatedByString(" / ")
// Insert foodAndAmount[0] into foodName
// Insert foodAndAmount[1] into foodUnit
}
EDIT: Apologize for the indentation.