How do I take a substring to the first index of a character? - swift

I'm very new to Swift; I've spent the morning reading StackOverflow and trying many strategies, in vain, to accomplish the following:
I have a string, say "12345 is your number!"
I want to extract "12345" to a variable.
In Java, I'd do something like:
String myStr = "12345 is your number!";
return myStr.substring(0, myStr.indexOf(" "));
How do I do something similar in Swift? I don't want to hard-code any assumptions about what the ending index will be. It might be 5 characters in, it might not. I just want to take the substring of everything up to the first occurrence of " ", wherever that might be.
The closest I've gotten so far is:
var myMessage = "12345 is your number!"
myMessage.endIndex.advancedBy(myMessage.characters.count - myMessage.characters.indexOf(" "))
but it doesn't compile for reasons I don't fully yet grok("Binary operator '-' cannot be applied to operands of type Distance (aka 'Int') and 'String.CharacterView.Index?'")
Any help on this is appreciated. Thank you.

Something like this should work:
myMessage.substringToIndex(myMessage.characters.indexOf(" ")!)
Note that in this code I force unwrapped the optional. If you're not guaranteed to have that space in the string, it might make more sense to have the index in a optional binding.
With optional binding, it would look something like this:
if let index = myMessage.characters.indexOf(" ") {
let result = myMessage.substringToIndex(index)
}

You can use a regex, try this code:
var myMessage = "12345 is your number!"
if let match = myMessage.rangeOfString("-?\\d+", options: .RegularExpressionSearch) {
print(myMessage.substringWithRange(match)) // 12345
let myNumber = Int(myMessage.substringWithRange(match)) // Then you can initialize a new variable
}
The advantage is that this method extracts only the numbers wherever they are in the String
Hope this help ;)

With Swift 5 you can use:
myStr.prefix(upTo: myStr.firstIndex(of: " ") ?? myStr.startIndex)
You may need to cast it back to String (String(myStr.prefix(upTo: myStr.firstIndex(of: " ") ?? myStr.startIndex))) since it returns a Substring

Related

what is the best way to write this function? [duplicate]

just a short question. In Swift it is possible to solve the following code:
var a: String;
a = "\(3*3)";
The arithmetic operation in the string will be solved. But i can´t figure out, why this following variation doesn´t work.
var a: String;
var b: String;
b = "3*3";
a = "\(b)";
In this case the arithmetic operation in var a will not be resolved. Any ideas why and how i can this get to work. Some things would be much more easier if this would work. Thanks for your answers.
In the second case, you are interpolating a string, not an arithmetic expression. In your example, it's a string you chose at compile time, but in general it might be a string from the user, or loaded from a file or over the web. In other words, at runtime b could contain some arbitrary string. The compiler isn't available at runtime to parse an arbitrary string as arithmetic.
If you want to evaluate an arbitrary string as an arithmetic formula at runtime, you can use NSExpression. Here's a very simple example:
let expn = NSExpression(format:"3+3")
println(expn.expressionValueWithObject(nil, context: nil))
// output: 6
You can also use a third-party library like DDMathParser.
Swift 4.2
let expn = "3+3"
print(expn.expressionValue(with: nil, context: nil))
But I also have a solution thats not the most effective way but could be used in some cases if your sure it's only "y+x" and not longer string.
var yNumber: Int!
var xNumber: Int!
let expn: String? = "3+3"
// Here we take to first value in the expn String.
if let firstNumber = expo?.prefix(1), let myInt = Int(firstNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to yNumber
yNumber = myInt
}
// Here we take the last value in the expn string
if let lastNumber = optionalString?.suffix(1), let myInt = Int(lastNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to xNumber
xNumber = myInt
}
// Now you can take the two numbers and add
print(yNumber + xNumber)
// will print (6)
I can't recommend this but it works in some cases
This won't be solved because this is not an arithmetic operation, this is a string:
"3*3"
the same as this
"String"
Everything you put in " it's a string.
The second example lets you construct a new String value from a mix of constants, variables, literals, and expressions:
"\(3*3)"
this is possible because of string interpolation \()
You inserted a string expression which swing convert and create expected result.
You can try to use evaluatePostfixNotationString method from that class.
The whole project is about recognizing math expression from camera image and calculating it after.

Need some help for swift substring

var t = "13,45,344"
print(t.prefix(upTo: t.firstIndex(of: ",")))
results in error: value of optional type 'String.Index?' must be unwrapped to a value of type 'String.Index'
print(t.prefix(upTo: t.firstIndex(of: ",")))
SWIFT makes me crazy
You need to define the behavior you want when there is no comma. I assume you would like to print the whole thing. In that case you don't need indexes at all. You want "prefix as long as the current character is not comma:"
print(t.prefix(while: { $0 != "," }))
Minimal no crashing version of your code with supporting for NO COMMA situation:
if let prefix = t.firstIndex(of: ",") {
print(t.prefix(upTo: prefix))
} else {
print(t)
}
Or even more simpler mentioned by #rmaddy:
print(t.prefix(upTo: t.firstIndex(of: ",") ?? t.endIndex))

Swift 3 capitalize string

let first = postalText.text?[(postalText.text?.startIndex)!]
let second = postalText.text?[(postalText.text?.index((postalText.text?.startIndex)!, offsetBy: 1))!]
let third = postalText.text?[(postalText.text?.index((postalText.text?.startIndex)!, offsetBy: 2))!]
I'm trying to capitalize the FIRST and THIRD character and then merge all 3 into a new string
but the .uppercase and .capitalized doesn't work .
Also how do i check that the SECOND character is a number ?
.uppercased and .capitalized only work for strings, what you show there are Characters. You can cast a Character as a String and make it capitalized.
let firstCapitalized = String(first!).capitalized
If you want to check if a Character is an int, you can also make it a String, and then check if casting the String as an Int is non-nil:
if Int("\(second!)") != nil {
print("Is Integer")
}
These cases all assume your first, second, and third are all non-nil, and force-unwraps them.
EDIT
I had some free time and was overlooking some old posts on SO, and I realized this answer I posted isn't using the best coding form. First off, force unwrapping anything is always a bad idea (it's a recipe for a crash in the future), so for the first part. Do something like this:
let firstCapitalized = String(first ?? "").capitalized
This at least gives you a back-out in case first == nil then you'll just be stuck with an empty string.
For the second part, I would use optional unwrapping instead of if Int("\(second!)") != nil. I would say the more proper method would be something like this:
if let second = second, let stringConvertedToInteger = Int("\(String(second))") {
print("\(stringConvertedToInteger) is an integer")
} else {
print("Either second is nil, or it cannot be converted to an integer")
}
This will optionally unwrap the character second, and if it has a value, convert it to an integer (should it be one, checked by optional unwrapping). This is the safest way to do it, and will keep you from experiencing any runtime errors.

Swift: Remove text from string [duplicate]

I'm very new to Swift; I've spent the morning reading StackOverflow and trying many strategies, in vain, to accomplish the following:
I have a string, say "12345 is your number!"
I want to extract "12345" to a variable.
In Java, I'd do something like:
String myStr = "12345 is your number!";
return myStr.substring(0, myStr.indexOf(" "));
How do I do something similar in Swift? I don't want to hard-code any assumptions about what the ending index will be. It might be 5 characters in, it might not. I just want to take the substring of everything up to the first occurrence of " ", wherever that might be.
The closest I've gotten so far is:
var myMessage = "12345 is your number!"
myMessage.endIndex.advancedBy(myMessage.characters.count - myMessage.characters.indexOf(" "))
but it doesn't compile for reasons I don't fully yet grok("Binary operator '-' cannot be applied to operands of type Distance (aka 'Int') and 'String.CharacterView.Index?'")
Any help on this is appreciated. Thank you.
Something like this should work:
myMessage.substringToIndex(myMessage.characters.indexOf(" ")!)
Note that in this code I force unwrapped the optional. If you're not guaranteed to have that space in the string, it might make more sense to have the index in a optional binding.
With optional binding, it would look something like this:
if let index = myMessage.characters.indexOf(" ") {
let result = myMessage.substringToIndex(index)
}
You can use a regex, try this code:
var myMessage = "12345 is your number!"
if let match = myMessage.rangeOfString("-?\\d+", options: .RegularExpressionSearch) {
print(myMessage.substringWithRange(match)) // 12345
let myNumber = Int(myMessage.substringWithRange(match)) // Then you can initialize a new variable
}
The advantage is that this method extracts only the numbers wherever they are in the String
Hope this help ;)
With Swift 5 you can use:
myStr.prefix(upTo: myStr.firstIndex(of: " ") ?? myStr.startIndex)
You may need to cast it back to String (String(myStr.prefix(upTo: myStr.firstIndex(of: " ") ?? myStr.startIndex))) since it returns a Substring

Swift - Resolving a math operation in a string

just a short question. In Swift it is possible to solve the following code:
var a: String;
a = "\(3*3)";
The arithmetic operation in the string will be solved. But i can´t figure out, why this following variation doesn´t work.
var a: String;
var b: String;
b = "3*3";
a = "\(b)";
In this case the arithmetic operation in var a will not be resolved. Any ideas why and how i can this get to work. Some things would be much more easier if this would work. Thanks for your answers.
In the second case, you are interpolating a string, not an arithmetic expression. In your example, it's a string you chose at compile time, but in general it might be a string from the user, or loaded from a file or over the web. In other words, at runtime b could contain some arbitrary string. The compiler isn't available at runtime to parse an arbitrary string as arithmetic.
If you want to evaluate an arbitrary string as an arithmetic formula at runtime, you can use NSExpression. Here's a very simple example:
let expn = NSExpression(format:"3+3")
println(expn.expressionValueWithObject(nil, context: nil))
// output: 6
You can also use a third-party library like DDMathParser.
Swift 4.2
let expn = "3+3"
print(expn.expressionValue(with: nil, context: nil))
But I also have a solution thats not the most effective way but could be used in some cases if your sure it's only "y+x" and not longer string.
var yNumber: Int!
var xNumber: Int!
let expn: String? = "3+3"
// Here we take to first value in the expn String.
if let firstNumber = expo?.prefix(1), let myInt = Int(firstNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to yNumber
yNumber = myInt
}
// Here we take the last value in the expn string
if let lastNumber = optionalString?.suffix(1), let myInt = Int(lastNumber){
// This will print (Int : 3)
print("Int : \(myInt)")
// I set the value to xNumber
xNumber = myInt
}
// Now you can take the two numbers and add
print(yNumber + xNumber)
// will print (6)
I can't recommend this but it works in some cases
This won't be solved because this is not an arithmetic operation, this is a string:
"3*3"
the same as this
"String"
Everything you put in " it's a string.
The second example lets you construct a new String value from a mix of constants, variables, literals, and expressions:
"\(3*3)"
this is possible because of string interpolation \()
You inserted a string expression which swing convert and create expected result.
You can try to use evaluatePostfixNotationString method from that class.
The whole project is about recognizing math expression from camera image and calculating it after.