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

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

Related

Cant iterate over vec<&str> and pass element into option_env!()? [duplicate]

This question already has answers here:
println! error: expected a literal / format argument must be a string literal
(4 answers)
What does the word "literal" mean?
(11 answers)
Closed last month.
Sorry if this is a noob question.
I've created a .cargo/config.toml file in my project and configured some env variables like so:
[env]
GAME_ZERO_LEVEL = "0"
GAME_ZERO_MULTIPLIER = "0.1"
GAME_ONE_LEVEL = "1"
GAME_ONE_MULTIPLIER = "1.0"
GAME_TWO_LEVEL = "2"
GAME_TWO_MULTIPLIER = "2.5"
GAME_THREE_LEVEL = "3"
GAME_THREE_MULTIPLIER = "5.0"
GAME_FOUR_LEVEL = "4"
GAME_FOUR_MULTIPLIER = "10.0"
I will parse these into u32 and f32.
Anyway, I'm able to fetch these individually with
let value = option_env!("GAME_ZERO_LEVEL").unwrap();
Here is the problem, I want to fetch all env variables in a loop like so:
let env_keys: Vec<&str> = vec![
"GAME_ZERO_LEVEL",
"GAME_ZERO_MULTIPLIER",
"GAME_ONE_LEVEL",
"GAME_ONE_MULTIPLIER",
"GAME_TWO_LEVEL",
"GAME_TWO_MULTIPLIER",
"GAME_THREE_LEVEL",
"GAME_THREE_MULTIPLIER",
"GAME_FOUR_LEVEL",
"GAME_FOUR_MULTIPLIER",
];
env_keys.iter().for_each(|key| {
let value = option_env!(key).unwrap(); //error here
// do some stuff with it
}
But I get the following compile error
rustc: argument must be a string literal
Safe to say, Im pretty confused as my previous understanding was that &str are string literals, and that passing in a &str in a variable doesnt't work. Any help understanding this would be much appreciated!
Note: I cant use std::env::{var, vars}
Slight misconception there &str or more specifically &'static stris the type of string literals but string literals are just the ones you type literally like this: "this is a string literal", or this r"I'm a raw string literal" or even like this r#"I'm a raw string literal which can contain " wherever"#. Everything else is not a literal. Things that are not string literals also can have that type though.
Compare also string literals in Rust by example and the reference
option_env!() evaluates it's contents at compile time so you can't use it with runtime variables like your key.

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 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 replace string into string in Swift? [duplicate]

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")

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