How can I create a list of words that contains upper case letters in swift? - string

I would like to generate a list of words form a given string where each listed word contains at least an upper case letter.
Having a string like this one:
let str: String = "Apple watchOS 3 USA release date and feature rumours."
I would like to get an array like this:
var list: [String] = ["Apple", "watchOS", "USA"]
What is the best way to do this?

var list = str.componentsSeparatedByString(" ").filter{ $0.lowercaseString != $0 }

You can use built in function of String in Swift that get all words of a string. It's better than just separate by a space (" ") cause you can have some words with a point (like the example below)
let str = "Apple watchOS 3 USA release date and feature Rumours."
var list = [String]()
str.enumerateSubstringsInRange(str.startIndex..<str.endIndex, options:.ByWords) {
(substring, substringRange, enclosingRange, value) in
//add to your array if lowercase != string original
if let _subString = substring where _subString.lowercaseString != _subString {
list.append(_subString)
}
}

You can probably do something like this. I haven't tested it, just wrote it real quick.
let str = "Apple watchOS 3 USA release date and feature rumours."
let strArr = str.componentsSeparatedByString(" ")
var upperWords: Array<String> = []
for word in strArr {
if word != word.lowercaseString {
upperWords.append(word)
}
}

Related

swift/parse: incrementing strings

The Swift part of the question:
So what I mean by incrementing strings is that say we start off with var string = "title" I want to be able to increment numbers to the end of that like "title1", "title2", "title3...". Should I use a for loop to do this? If so, how? Or another method?
for var i = 1; i < 6; i = i + 1 {
//increment the strings here
}
The Parse part of the question:
I want to have my objectForKey use the many different titles and numbers we will produce above so that the objectForKey will be "title1", "title2", "title3"... I would make multiple columns on Parse with names " title1, title2, title3 and the cells in the tableview would correspond to that data. So cell1 would use title1's data, cell2 will use title2's data and so on. Will it work like this?
var output1 = object.objectForKey(i) as! String
A loop in Swift is like for i in 1...5, and then you can use string interpolation to get the correct string like this:
for i in 1...5 {
let title = "title\(i)"
print(title)
}
Also read Dan's answer.
There are a few ways of looping in Swift, but you should keep in mind that and as of Swift 3,
this will no longer be one of them:
for var i = 0; i <6; i++ {
let string = "title\(i+1)"
}
source : Swift Evolution
Swift's preferred way of general looping is, as GvS stated:
for i in 1...5 {
let title = "title\(i)"
}
However, you are also welcome to use Swifts higher order functions to loop:
(1...5).forEach { i in
let title = "title \(i)"
}
or
(1...5).forEach { let title = "title \($0)" }

Swift How to get integer from string and convert it into integer

I need to extract numbers from string and put them into a new array in Swift.
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
I tried to loop each characters and I have no idea to compare between Characters and Int.
Swift 3/4
let string = "0kaksd020dk2kfj2123"
if let number = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) {
// Do something with this number
}
You can also make an extension like:
extension Int {
static func parse(from string: String) -> Int? {
return Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
}
And then later use it like:
if let number = Int.parse(from: "0kaksd020dk2kfj2123") {
// Do something with this number
}
First, we split the string so we can process the single items. Then we use NSCharacterSet to select the numbers only.
import Foundation
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let strArr = str.split(separator: " ")
for item in strArr {
let part = item.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
if let intVal = Int(part) {
print("this is a number -> \(intVal)")
}
}
Swift 4:
let string = "I have to buy 3 apples, 7 bananas, 10eggs"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
if let number = Int(item) {
print("number: \(number)")
}
}
Using the "regex helper function" from Swift extract regex matches:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
let regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)!
let nsString = text as NSString
let results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
return map(results) { nsString.substringWithRange($0.range)}
}
you can achieve that easily with
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let numbersAsStrings = matchesForRegexInText("\\d+", str) // [String]
let numbersAsInts = numbersAsStrings.map { $0.toInt()! } // [Int]
println(numbersAsInts) // [3, 7, 10]
The pattern "\d+" matches one or more decimal digit.
Of course the same can be done without the use of a helper function
if you prefer that for whatever reason:
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let regex = NSRegularExpression(pattern: "\\d+", options: nil, error: nil)!
let nsString = str as NSString
let results = regex.matchesInString(str, options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
let numbers = map(results) { nsString.substringWithRange($0.range).toInt()! }
println(numbers) // [3, 7, 10]
Alternative solution without regular expressions:
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let digits = "0123456789"
let numbers = split(str, allowEmptySlices: false) { !contains(digits, $0) }
.map { $0.toInt()! }
println(numbers) // [3, 7, 10]
let str = "Hello 1, World 62"
let intString = str.componentsSeparatedByCharactersInSet(
NSCharacterSet
.decimalDigitCharacterSet()
.invertedSet)
.joinWithSeparator("")
That will get you a string with all the number then you can just do this:
let int = Int(intString)
Just make sure you unwrap it since let int = Int(intString) is an optional.
For me makes more sense to have it as a String extension, probably it's a matter of tastes:
extension String {
func parseToInt() -> Int? {
return Int(self.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
}
So can be used like this:
if let number = "0kaksd020dk2kfj2123".parseToInt() {
// Do something with this number
}
Adapting from #flashadvanced's answer,
I found that the following is shorter and simpler for me.
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let component = str.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let list = component.filter({ $0 != "" }) // filter out all the empty strings in the component
print(list)
Tried in in the play ground and it works
Hope it helps :)
Swift 2.2
let strArr = str.characters.split{$0 == " "}.map(String.init)
for item in strArr {
let components = item.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let part = components.joinWithSeparator("")
if let intVal = Int(part) {
print("this is a number -> \(intVal)")
}
}
// This will only work with single digit numbers. Works with “10eggs” (no space between number and word
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
var ints: [Int] = []
for char:Character in str {
if let int = "\(char)".toInt(){
ints.append(int)
}
}
The trick here is that you can check if a string is an integer (but you can’t check if a character is).
By looping though every character of the string, use string interpolation to create a string from the character and check if that string cas be casted as a integer.
If it can be, add it to the array.
// This will work with multi digit numbers. Does NOT work with “10 eggs” (has to have a space between number and word)
var str = "I have to buy 3 apples, 7 bananas, 10 eggs"
var ints: [Int] = []
var strArray = split(str) {$0 == " "}
for subString in strArray{
if let int = subString.toInt(){
ints.append(int)
}
}
Here we split the string at any space and create an array of every substring that is in the long string.
We again check every string to see if it is (or can be casted as) an integer.
Thanks for everyone who answered to my question.
I was looking for a block of code which uses only swift grammar, because I'm learning grammar only now..
I got an answer for my question.Maybe it is not an easier way to solve, but it uses only swift language.
var article = "I have to buy 3 apples, 7 bananas, 10 eggs"
var charArray = Array(article)
var unitValue = 0
var total = 0
for char in charArray.reverse() {
if let number = "\(char)".toInt() {
if unitValue==0 {
unitValue = 1
}
else {
unitValue *= 10
}
total += number*unitValue
}
else {
unitValue = 0
}
}
println("I bought \(total) apples.")
Swift 5:
extension String {
var allNumbers: [Int] {
let numbersInString = self.components(separatedBy: .decimalDigits.inverted).filter { !$0.isEmpty }
return numbersInString.compactMap { Int($0) }
}
}
You can get all numbers like
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
// numbers = [3, 7, 10]
numbers = str.allNumbers

Remove some text from a string after some constant value(string)

Input: String str="Fund testing testing";
Output: str="Fund";
After fund whatever the text is there need to remove that text.
Please suggest some solution.
The easiest way to solve this is a .Substring() method, as you can provide it the start index of your original string and length of the string you need:
var length = "Fund".Length;
var str = "Fund testing testing";
Console.WriteLine(str.Substring(0, length)); //returns "Fund"
var str1 = "testFund testing testing";
Console.WriteLine(str1.Substring(4, length)); //returns "Fund"
var str2 = "testFund testing testing";
Console.WriteLine(str2.Substring(str2.IndexOf("Fund"), length)); //returns "Fund"
You can also use regular expression like this:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
string strTargetString = #"Fund testing testing";
string strReplace = #"$1";
return myRegex.Replace(strTargetString, strReplace);
As mentioned in comments below, replace can lack performance and is kind of overkill, so regex Match can be better. Here is how it looks like:
string strRegex = #".*?(Fund).*";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = "\n\n" + #" Fund testing testing";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var fund = myMatch.Groups[1].Value;
Console.WriteLine(fund);
}
}
Note that Groups first element is your entire match

Swift - Finding a substring between two locations in a string

I have a string that is formatted like this: "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|"
Basiclly its an ID;ID| and then it repeats.
I have the first ID and I need to find it's partner Example: I have 'Piida' and I need to find the String that follows it after the ';' which is 'bfedsSA'
How do I do this?
The problem I am having is that the length of the IDs is dynamic so I need to get the index of '|' after the ID I have which is 'Piida' and then get the string that is between these indexes which in this case should be 'bfedsSA'.
There are many ways to do this, but the easiest is to split the string into an array using a separator.
If you know JavaScript, it's the equivalent of the .split() string method; Swift does have this functionality, but as you see there, it can get a little messy. You can extend String like this to make it a bit simpler. For completeness, I'll include it here:
import Foundation
extension String {
public func split(separator: String) -> [String] {
if separator.isEmpty {
return map(self) { String($0) }
}
if var pre = self.rangeOfString(separator) {
var parts = [self.substringToIndex(pre.startIndex)]
while let rng = self.rangeOfString(separator, range: pre.endIndex..<endIndex) {
parts.append(self.substringWithRange(pre.endIndex..<rng.startIndex))
pre = rng
}
parts.append(self.substringWithRange(pre.endIndex..<endIndex))
return parts
} else {
return [self]
}
}
}
Now, you can call .split() on strings like this:
"test".split("e") // ["t", "st"]
So, what you should do first is split up your ID string into segments by your separator, which will be |, because that's how your IDs are separated:
let ids: [String] = "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|".split("|")
Now, you have a String array of your IDs that would look like this:
["XbfdASF;FBACasc", "Piida;bfedsSA", "XbbnSF;vsdfAs"]
Your IDs are in the format ID;VALUE, so you can split them again like this:
let pair: [String] = ids[anyIndex].split(";") // ["ID", "VALUE"]
You can access the ID at index 0 of that array and the value at index 1.
Example:
let id: String = ids[1].split(";")[0]
let code: String = ids[1].split(";")[1]
println("\(id): \(code)") // Piida: bfedsSA

Remove last character from string. Swift language

How can I remove last character from String variable using Swift? Can't find it in documentation.
Here is full example:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
Swift 4.0 (also Swift 5.0)
var str = "Hello, World" // "Hello, World"
str.dropLast() // "Hello, Worl" (non-modifying)
str // "Hello, World"
String(str.dropLast()) // "Hello, Worl"
str.remove(at: str.index(before: str.endIndex)) // "d"
str // "Hello, Worl" (modifying)
Swift 3.0
The APIs have gotten a bit more swifty, and as a result the Foundation extension has changed a bit:
var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name) // "Dolphin"
print(truncated) // "Dolphi"
Or the in-place version:
var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name) // "Dolphi"
Thanks Zmey, Rob Allen!
Swift 2.0+ Way
There are a few ways to accomplish this:
Via the Foundation extension, despite not being part of the Swift library:
var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name) // "Dolphin"
print(truncated) // "Dolphi"
Using the removeRange() method (which alters the name):
var name: String = "Dolphin"
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"
Using the dropLast() function:
var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name) // "Dolphin"
print(truncated) // "Dolphi"
Old String.Index (Xcode 6 Beta 4 +) Way
Since String types in Swift aim to provide excellent UTF-8 support, you can no longer access character indexes/ranges/substrings using Int types. Instead, you use String.Index:
let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"
Alternatively (for a more practical, but less educational example) you can use endIndex:
let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"
Note: I found this to be a great starting point for understanding String.Index
Old (pre-Beta 4) Way
You can simply use the substringToIndex() function, providing it one less than the length of the String:
let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"
The global dropLast() function works on sequences and therefore on Strings:
var expression = "45+22"
expression = dropLast(expression) // "45+2"
// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())
Swift 4:
let choppedString = String(theString.dropLast())
In Swift 2, do this:
let choppedString = String(theString.characters.dropLast())
I recommend this link to get an understanding of Swift strings.
Swift 4/5
var str = "bla"
str.removeLast() // returns "a"; str is now "bl"
This is a String Extension Form:
extension String {
func removeCharsFromEnd(count_:Int) -> String {
let stringLength = count(self)
let substringIndex = (stringLength < count_) ? 0 : stringLength - count_
return self.substringToIndex(advance(self.startIndex, substringIndex))
}
}
for versions of Swift earlier than 1.2:
...
let stringLength = countElements(self)
...
Usage:
var str_1 = "Maxim"
println("output: \(str_1.removeCharsFromEnd(1))") // "Maxi"
println("output: \(str_1.removeCharsFromEnd(3))") // "Ma"
println("output: \(str_1.removeCharsFromEnd(8))") // ""
Reference:
Extensions add new functionality to an existing class, structure, or enumeration type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories, Swift extensions do not have names.)
See DOCS
Use the function removeAtIndex(i: String.Index) -> Character:
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
Swift 4
var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])
or
welcome.remove(at: welcome.index(before: welcome.endIndex))
or
welcome = String(welcome.dropLast())
The easiest way to trim the last character of the string is:
title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]
import UIKit
var str1 = "Hello, playground"
str1.removeLast()
print(str1)
var str2 = "Hello, playground"
str2.removeLast(3)
print(str2)
var str3 = "Hello, playground"
str3.removeFirst(2)
print(str3)
Output:-
Hello, playgroun
Hello, playgro
llo, playground
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
var str = "Hello, playground"
extension String {
var stringByDeletingLastCharacter: String {
return dropLast(self)
}
}
println(str.stringByDeletingLastCharacter) // "Hello, playgroun"
Short answer (valid as of 2015-04-16): removeAtIndex(myString.endIndex.predecessor())
Example:
var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"
Meta:
The language continues its rapid evolution, making the half-life for many formerly-good S.O. answers dangerously brief. It's always best to learn the language and refer to real documentation.
With the new Substring type usage:
Swift 4:
var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world
Shorter way:
var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world
Use the function advance(startIndex, endIndex):
var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))
A swift category that's mutating:
extension String {
mutating func removeCharsFromEnd(removeCount:Int)
{
let stringLength = count(self)
let substringIndex = max(0, stringLength - removeCount)
self = self.substringToIndex(advance(self.startIndex, substringIndex))
}
}
Use:
var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"
Another way If you want to remove one or more than one character from the end.
var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)
Where XX is the number of characters you want to remove.
Swift 3 (according to the docs) 20th Nov 2016
let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)
The dropLast() function removes the last element of the string.
var expression = "45+22"
expression = expression.dropLast()
Swift 4.2
I also delete my last character from String (i.e. UILabel text) in IOS app
#IBOutlet weak var labelText: UILabel! // Do Connection with UILabel
#IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button
labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it
}
I'd recommend using NSString for strings that you want to manipulate. Actually come to think of it as a developer I've never run into a problem with NSString that Swift String would solve... I understand the subtleties. But I've yet to have an actual need for them.
var foo = someSwiftString as NSString
or
var foo = "Foo" as NSString
or
var foo: NSString = "blah"
And then the whole world of simple NSString string operations is open to you.
As answer to the question
// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)
Swift 3: When you want to remove trailing string:
func replaceSuffix(_ suffix: String, replacement: String) -> String {
if hasSuffix(suffix) {
let sufsize = suffix.count < count ? -suffix.count : 0
let toIndex = index(endIndex, offsetBy: sufsize)
return substring(to: toIndex) + replacement
}
else
{
return self
}
}
complimentary to the above code I wanted to remove the beginning of the string and could not find a reference anywhere. Here is how I did it:
var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range) // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description
This trims 17 characters from the beginning of the string (he total string length is 67 we advance -50 from the end and there you have it.
I prefer the below implementation because I don't have to worry even if the string is empty
let str = "abc"
str.popLast()
// Prints ab
str = ""
str.popLast() // It returns the Character? which is an optional
// Print <emptystring>

Resources