Using Swift's Repeat collection - swift2

In pre-Swift 2.0 sample code, I've come across something like:
var val = "hello" + Repeat(count: paddingAmount, repeatedValue: "-") + "."
In Xcode 7.0/Swift 2.0 Playground, this produces the error:
note: expected an argument list of type '(String, String)'
How would you use the Repeat collection and get the value that's held by the collection for use?

String has an initializer that will return a string of repeated characters, I would recommend using that in your case:
let padding = String(count: paddingAmount, repeatedValue: Character("-"))
var val = "hello" + padding + "."

It's now Array(count: paddingAmount, repeatedValue: "-").

Related

How to call repeat fun within replace range in Kotlin

I got this code
val numberOfStars = urlString.length - index
val result = urlString.replaceRange(index+1..urlString.length - 1,"*") //Here
I need to repeat replacing of character with "*" by numberOfStars. Now it replace only once. And I have result like this somehere=* but I need if numberOfStars=5 the result will be somehere=*****
AFAIK there is no method out of the box .... but you can do it like
val result = urlString.replaceRange(index+1..urlString.length - 1,"*".repeat(numberOfStars))
Since you want to replace everything from index to the end of the string, it is not really necessary to use replaceRange. The following is a bit less redundant, because you do not need to write the length of the urlString twice:
val numberOfStars = urlString.length - index
val result = urlString.substring(0, index + 1) + "*".repeat(numberOfStars)
It would also be possible to do it like this:
val result = urlString.mapIndexed { i, c -> if(i > index) "*" else c }
.joinToString(separator = "")

xcode: need to convert strings to double and back to string

this is my line of code.
budgetLabel.text = String((budgetLabel.text)!.toInt()! - (budgetItemTextBox.text)!.toInt()!)
the code works, but when I try to input a floating value into the textbox the program crashes. I am assuming the strings need to be converted to a float/double data type. I keep getting errors when i try to do that.
In Swift 2 there are new failable initializers that allow you to do this in more safe way, the Double("") returns an optional in cases like passing in "abc" string the failable initializer will return nil, so then you can use optional-binding to handle it like in the following way:
let s1 = "4.55"
let s2 = "3.15"
if let n1 = Double(s1), let n2 = Double(s2) {
let newString = String( n1 - n2)
print(newString)
}
else {
print("Some string is not a double value")
}
If you're using a version of Swift < 2, then old way was:
var n1 = ("9.99" as NSString).doubleValue // invalid returns 0, not an optional. (not recommended)
// invalid returns an optional value (recommended)
var pi = NSNumberFormatter().numberFromString("3.14")?.doubleValue
Fixed: Added Proper Handling for Optionals
let budgetLabel:UILabel = UILabel()
let budgetItemTextBox:UITextField = UITextField()
budgetLabel.text = ({
var value = ""
if let budgetString = budgetLabel.text, let budgetItemString = budgetItemTextBox.text
{
if let budgetValue = Float(budgetString), let budgetItemValue = Float(budgetItemString)
{
value = String(budgetValue - budgetItemValue)
}
}
return value
})()
You need to be using if let. In swift 2.0 it would look something like this:
if let
budgetString:String = budgetLabel.text,
budgetItemString:String = budgetItemTextBox.text,
budget:Double = Double(budgetString),
budgetItem:Double = Double(budgetItemString) {
budgetLabel.text = String(budget - budgetItem)
} else {
// If a number was not found, what should it do here?
}

Swift adding multiple stringByReplacingOccurrencesOfString on one String?

Hello i would like to create a app that changes characters into binary code and i was wondering if there is a way to add multiple stringByReplacingOccurrencesOfString on one String or if i should take another approach to this "Problem".
Here is what i have so far
func textToBinary(theString: String) -> String {
return theString.stringByReplacingOccurrencesOfString("a",
withString: "01100001")
}
textArea.text = textToBinary(lettersCombined)
// lettersCombined is the string that i want to turn into BinaryCode.
Try this:
func textToBinary(theString : String, radix : Int = 2) -> String {
var result = ""
for c in theString.unicodeScalars {
result += String(c.value, radix: radix) + " "
}
return result
}
println(textToBinary("a"))
println(textToBinary("abc", radix: 10))
println(textToBinary("€20", radix: 16))
println(textToBinary("😄"))
(The last one is a smiley face but somehow my browser can't display it).
Edit: if you want to pad your strings to 8-character long, try this:
let str = "00000000" + String(c.value, radix: radix)
result += str.substringFromIndex(advance(str.startIndex, str.characters.count - 8)) + " "
The first line adds eight 0 the left of your string. The second line takes the last 8 characters from the padded string.

How do I extract numbers from a string in VB6?

I have a string that looks something like 'NS-BATHROOMS 04288'
I only want the numbers.
I hve searched for answers, but none so far even get pst the compiler.
How can I do this?
without regex you can do it with: (altough VB6/VBA Code really isn`t nice to look at)
Public Function ReturnNonAlpha(ByVal sString As String) As String
Dim i As Integer
For i = 1 To Len(sString)
If Mid(sString, i, 1) Like "[0-9]" Then
ReturnNonAlpha = ReturnNonAlpha + Mid(sString, i, 1)
End If
Next i
End Function
I'd personally use regex. You can match given regex patterns to achieve what you need. This function matches only digits.
For VB6 you'd do something like:
Dim myRegExp, ResultString
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = "[\d]"
Then you'd go against your String.
https://support.microsoft.com/en-us/kb/818802
You can use this function for extract numerical chr as string value:
Public Function Str_To_Int(MyString As Variant) As Long
Dim i As Integer
Dim X As Variant
If IsNull(MyString) Or MyString = "" Then
Str_To_Int = 0
Exit Function
End If
For i = 1 To Len(MyString)
If IsNumeric(Mid(MyString, i, 1)) = True Then
X = Nz(X, "") & Mid(MyString, i, 1)
End If
Next i
Str_To_Int = Nz(X, 0)
End Function

How can I concatenate strings only if they have passed a logical statement in Swift?

My challenge is twofold:
To pick individual strings from an array of similar strings, but only if a boolean test has been passed first.
"Finally" I need to concatenate any/all of the strings generated into one complete text and the entire code must be in Swift.
Illustration: A back of the envelope code for illustration of logic:
generatedText.text =
case Int1 <= 50 && Int2 == 50
return generatedParagraph1 = pick one string at RANDOM from a an array1 of strings
case Int3 =< 100
return generatedParagraph2 = pick one string at RANDOM from a an array2 of strings
case Int4 == 100
return generatedParagraph3 = pick one string at RANDOM from a an array3 of strings
...etc
default
return "Nothing to report"
and concatenate the individual generatedParagraphs
Attempt: Code picks a random element within stringArray1, 2 and 3.
Example of what the code returns:
---> "Sentence1_c.Sentence2_a.Sentence3_b."
PROBLEM: I need the code to ONLY pick an element if it has first passed a boolean. It means that the final concatenated string (concastString) could be empty, just contain one element, or several depending on how many of the bools were True. Does anyone know how to do this?
import Foundation
var stringArray1 = ["","Sentence1_a.", "Sentence1_b.", "Sentence1_c."]
var stringArray2 = ["","Sentence2_a.", "Sentence2_b.", "Sentence2_c."]
var stringArray3 = ["","Sentence3_a.", "Sentence3_b.", "Sentence3_c."]
let count1 = UInt32(stringArray1.count)-1
let count2 = UInt32(stringArray2.count)-1
let count3 = UInt32(stringArray3.count)-1
var randomNumberOne = Int(arc4random_uniform(count1))+1
var randomNumberTwo = Int(arc4random_uniform(count2))+1
var randomNumberThree = Int(arc4random_uniform(count3))+1
let concatString = stringArray1[randomNumberOne] + stringArray2[randomNumberTwo] + stringArray3[randomNumberThree]
Okay, I didn't pass a Bool, but I show concatenating three random strings from a [String]. I ran this in a playground.
import Foundation
var stringArray = [String]()
for var i = 0; i < 100; i++ {
stringArray.append("text" + "\(i)")
}
func concat (array: [String]) -> String {
let count = UInt32(stringArray.count)
let randomNumberOne = Int(arc4random_uniform(count))
let randomNumberTwo = Int(arc4random_uniform(count))
let randomNumberThree = Int(arc4random_uniform(count))
let concatString = array[randomNumberOne] + array[randomNumberTwo] + array[randomNumberThree]
return concatString
}
let finalString = concat(stringArray)

Resources