How to replace string into string in Swift? [duplicate] - string

This question already has answers here:
Any way to replace characters on Swift String?
(23 answers)
Closed 8 years ago.
I want to replace some text in a string with another string.
For example : A string equals to "Red small car".
I want to replace "small" with "big" so the string becomes
"Red big car". I have to do this in swift. Thanks.

You can try using stringByReplacingOccurrencesOfString
let string = "Big red car"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString("Big", withString: "Small")
Edit
In Swift 5
import Foundation
let string = "Big red car"
let replaced = string.replacingOccurrences(of: "Big", with: "Small")

You can use stringByReplacingOccurrencesOfString, e.g.
let s1 : String = "Red small car"
let s2 = s1.stringByReplacingOccurrencesOfString("small", withString: "big")

Related

Swift 3.0 String concatenation leaves "Optional" [duplicate]

This question already has an answer here:
Swift 3 incorrect string interpolation with implicitly unwrapped Optionals
(1 answer)
Closed 6 years ago.
Since Swift 3.0 I have some troubles with Strings, especially with concatenation. 1st example would be what I used since I started using Swift to define my url strings.
internal let host: String! = "https://host.io/"
let urlString = "\(host)oauth/access_token"
where host is defined as at the beginning of the class. This worked perfectly until Swift 3.0, now that prints out like this:
Optional("https://host.io/")oauth/access_token
which is very strange. Now I have to write this
let urlString = host + "oauth/access_token"
To get the expected output.
https://host.io/oauth/access_token
Another - I guess similar problem I'm having with Strings is this. I'm again concatenating strings but this time I'm using + ilke with urlString - but this time that doesn't work. Line of code looks like this:
self.labelName.text = currentUser.name + " " + String(describing: ageComponents.year)
which unfortunately produces string like this: "My Name Optional(26)". In this case I don't have a solution String(describing: ageComponents.year) is not an optional and it doesn't allow me to do things like String(describing: ageComponents.year) ?? "whatever"
Anyone seen something similar?
In Swift 3 all properties of the native struct DateComponents are optionals unlike the Foundation NSDateComponents counterparts.
var year: Int? { get set }
You need to unwrap it. If you specified the unit year in ageComponents you can do that safely.

Swift - optional String vs. implicitly unwrapped optional String [duplicate]

This question already has answers here:
Swift variable decorations with "?" (question mark) and "!" (exclamation mark)
(1 answer)
What does an exclamation mark mean in the Swift language?
(23 answers)
Closed 7 years ago.
I was reading the Swift book published by Apple. According to the book:
var possibleString: String? = "an optional string"
var assumedString: String! = "an implicitly unwrapped optional string"
what's the difference between these two? And when should each one be used? It turns out both can even be set to nil.
Introduce another variable into your code:
var string: String
And then observe:
string = possibleString
The code above will fail with:
Value of optional type 'String?' not unwrapped, did you mean to use '!' or '?'?
However:
string = assumedString
works.
assumedString is automatically, or implicitly unwrapped for you. Use implicitly unwrapped optionals where you are certain that the optional contains a value.
use the first one when you cannot guaranty that there will be a string value when accessing the parameter.
use the second when you are 100% sure that there is a string value in this parameter when accessing it: for example, a username field parsing before sending it to validation on the server side, when you disable the login button press if this field is empty. so it means that if the login button was pressed, you have a string value in the text field, so it is guarantied to NOT to be nil.
p.s. in swift 2, use let and not var if your value will not be changed later...
From Apples Swift programming guide:
var possibleString: String? = "an optional string"
Optional is value is either contains a value or nil value to indicate the that the value is missing.
While using you have to use if and let together, as
var newString : String
if let possibleString = possibleString {
newString = possibleString
}
2.
var assumedString: String! = "an implicitly unwrapped optional string"
An implicitly unwrapped optional is similar to optional types but we can use it like a non optional value each time when it is accessed.
In this case you can use it directly as
var newString : String
newString = possibleString

Swift string strip all characters but numbers and decimal point?

I have this string:
Some text: $ 12.3 9
I want to get as a result:
12.39
I have found examples on how to keep only numbers, but here I am wanting to keep the decimal point "."
What's a good way to do this in Swift?
This should work (it's a general approach to filtering on a set of characters) :
[EDIT] simplified and adjusted to Swift3
[EDIT] adjusted to Swift4
let text = "$ 123 . 34 .876"
let decimals = Set("0123456789.")
var filtered = String( text.filter{decimals.contains($0)} )
If you need to ignore anything past the second decimal point add this :
filtered = filtered.components(separatedBy:".") // separate on decimal point
.prefix(2) // only keep first two parts
.joined(separator:".") // put parts back together
Easiest and simplest reusable way: you can use this regex replacement option. This replaces all characters except 0 to 9 and dot (.) .
let yourString = "$123. 34"
//pattern says except digits and dot.
let pattern = "[^0-9.]"
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
//replace all not required characters with empty string ""
let string_With_Just_Numbers_You_Need = regex.stringByReplacingMatchesInString(yourString, options: NSMatchingOptions.WithTransparentBounds, range: NSMakeRange(0, yourString.characters.count), withTemplate: "")
//your number converted to Double
let convertedToDouble = Double(string_With_Just_Numbers_You_Need)
} catch {
print("Cant convert")
}
One possible solution to the question follows below. If you're working with text fields and currency, however, I suggest you take a look at the thread Leo Dabus linked to.
extension String {
func filterByString(myFilter: String) -> String {
return String(self.characters.filter {
myFilter.containsString(String($0))
})
}
}
var a = "$ 12.3 9"
let myFilter = "0123456789.$"
print(a.filterByString(myFilter)) // $12.39

How to get last 4 characters of a string? [duplicate]

This question already has answers here:
How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
(33 answers)
Closed 7 years ago.
I need to seperate the last 4 letters of a string. How can I seperate it? The length of string is changing.
Example:
var a = "StackOverFlow"
var last4 = a.lastFour // That's what I want to do
print(last4) // prints Flow
Swift 2:
A solution is substringFromIndex
let a = "StackOverFlow"
let last4 = a.substringFromIndex(a.endIndex.advancedBy(-4))
or suffix on characters
let last4 = String(a.characters.suffix(4))
Swift 3:
In Swift 3 the syntax for the first solution has been changed to
let last4 = a.substring(from:a.index(a.endIndex, offsetBy: -4))
Swift 4+:
In Swift 4 it becomes more convenient:
let last4 = a.suffix(4)
The type of the result is a new type Substring which behaves as a String in many cases. However if the substring is supposed to leave the scope where it's created in you have to create a new String instance.
let last4 = String(a.suffix(4))
String substr = a.substring(a.length() - 4)
syntax is wrong. no type before vars in Swift.
let a = "1234567890"
let last4 = String(a.characters.suffix(4))
print(last4)
works on Swift 3.0

Parse one string to another [duplicate]

This question already has answers here:
How to get the last five characters of a string using Substring() in C#?
(12 answers)
Closed 9 years ago.
string A = "myString";
string B;
Is there a way to initiate B according to the data of A, so that value B changes with A.
B = capture change of A?
Edit: My initial post was not complete and misleading, I found the answer now. Still my question is a duplicate of observer pattern
Try this
B = A.Substring(0,2);
It initates B with substring of A from index 0 and lenght of 2
Sure, using String.Substring:
B = A.Substring(0,2); //"my"
You can try the following example
string A = "myString";
string B;
if (A.StartsWith("my"))
{
B = A.Substring(0, 2);//first two elements of A
}
Check out this Substring method

Resources