I'm going crazy with substrings in Swift. I need to get the actual index of a "string" inside another string to determine the range of my final output.
Any ideas?
Thanks
let yourString = "loremipsumSTRINGdolor" as NSString
let range: NSRange = yourString.rangeOfString("STRING")
let lenght = range.length
let location = range.location
This should do.
EDIT: Fix.
Related
i need to take only the integer from a string like this "Critical: 3\r\n" , note that the value change everytime so i can't search for "3", i need to search for a generic int.
Thanks.
Many ways to do it. There are already some answers. Here is one more approach:
let s = "Critical: 3\r\n";
let s_res = s.split(":").collect::<Vec<&str>>()[1].trim();
println!("s_res = {s_res:?}"); // "3"
In the above code s_res will be a string (&str). To convert that string to an integer, you can do something like this:
let n: isize = s_res.parse().expect("Failed to parse the integer!");
println!("n = {n}"); // 3
Note that, depending on your needs, you might want to add some extra validations/asserts, in case you expect the pattern might change (for example, the number of colons not to be 1, etc.).
Building on #AlexanderKrauze's comment the most common way to do so is using a regex, which lets you look for any pattern in a String:
let your_text = "Critical: 3\r\n";
let re = Regex::new(r"\d+").unwrap(); // matches any amount of consecutive digits
let result:Option<Match> = re.find(your_text);// returns the match
let number:u32 = result.map(|m| m.as_str().parse::<u32>().unwrap()).unwrap_or(0); // converts to int
print!("{}", number);
would be the code for that. Only one digit is r"\d".
More documentation is found here.
You can use chars to get an iterator over the chars of a string, and then apply filter on that iterator to filter out only digits(is_digit).
fn main() {
let my_str: String = "Critical: 3\r\n".to_owned();
let digits: String = my_str.chars().filter(|char| char.is_digit(10)).collect();
println!("{}", digits)
}
How do you convert a string into an observable ? I have json that is returning as a string and I need to convert it into a Observable type and I make not sure how to do that.
I'm not sure what you're looking for, but you can try this:
let stringObservable = Observable.just("your string here")
let boolObservableA = stringObservable.map(yourStringToBooleanMapper)
let boolObservableB = stringObservable.map{yourStringToBooleanMapper($0)}
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
I my app can read this string out of a QR Code, the amount of values differs per code
Example:
"<23><423><12><54>"
I would like to get each value which are separated by < & >
I thought of a loop which prints out each value. but im not really sure how to search for the values.
Thanks in advance
One possible solution:
let string = "<23><423><12><54>"
let nsString = string as NSString // (Works better with NSRegularExpression)
let regex = NSRegularExpression(pattern: "<(\\d+)>", options: nil, error: nil)!
regex.enumerateMatchesInString(nsString, options: nil, range: NSMakeRange(0, nsString.length)) {
(result, _, _) -> Void in
let code = nsString.substringWithRange(result.rangeAtIndex(1))
println(code)
}
"<(\\d+)>" is a regular expression pattern that matches one or more
digits enclosed in <...>, and the parentheses define a "capture group"
which is then extracted with result.rangeAtIndex(1).
I'm looking to find the last instance of a character in a string. Given the different way Swift deals with strings (ranges), I was hoping someone has run into this before as I can't seem to figure out the best way to deal with it.
The string I'd like to parse is similar to "http://imanimage_thatlooks_likethis_andmypixare_380.jpg". I need to parse the segment between the last "_" and the last ".". So the number 380. Each link is formatted this way, but the substring methodology for Swift is still a bit foreign to me, with the inclusion of different byte lengths.
Thanks in advance!
// regular expression to find substring between last "_" and last "."
let sourceStr = "abc_defg_hijk_lmn.xyz"
let regex = NSRegularExpression( pattern: "_([^_]*)\\.[^\\.]*$", options:nil, error:nil );
if let matchingResult = regex?.firstMatchInString( sourceStr, options: nil, range: NSMakeRange( 0, countElements( sourceStr ) ) ) {
let matchingRange = matchingResult.rangeAtIndex(1)
let matchingString = (sourceStr as NSString).substringWithRange( matchingRange )
}