How to store characters in string into an Array using Swift - arrays

Using Swift. How do I take a String and separate each character into an array?
var someString = "123"
var someArray = []
someArray[0] = "1"
someArray[1] = "2"
someArray[2] = "3"

Array has constructor that takes String and produce array of characters.
let someString = "abcde"
let array = Array(someString)

yes there are many ways to achieve this task old and best way is to use for in loop in the following way
var someString = "123"
var someArray : Array<Character> = []
for character in someString {
someArray.append(character)
}
println(someArray)

Related

Is there a way to convert a string array to a set? I am trying to use the symmetricDifference function found in the set class but it will not work

let chArr: [Character] = ["a","b","c","d","f"]
let stringList = String(describing: chArr)
let set1: Set = Set([stringList])
let lowerAlp = ["a", "b","c","d","e","f"]
let diff = set1.symmetricDifference(lowerAlp)
print(diff)
The first thing getting in your way is using let stringList = String(describing: chArr), which is giving you a string that reads "["a", "b", "c", "d", "f"]" -- in other words, not actually an Array, but rather a single string.
I'm unclear on whether you want to start with an Array of Character or String, but assuming you're truly starting with [Character] like in your example code, and you want to end up with Set<String>, you could do:
let chArr: [Character] = ["a","b","c","d","f"]
let stringList = Set(chArr.map { String($0) })
let lowerAlp = ["a","b","c","d","e","f"]
let diff = stringList.symmetricDifference(lowerAlp)
print(diff)
If you're starting with [String], it would be:
let stringList = Set(["a","b","c","d","f"])
let lowerAlp = ["a","b","c","d","e","f"]
let diff = stringList.symmetricDifference(lowerAlp)
print(diff)

Swift: Filter string by using start with

I have an array as follows:
let array = ["sam", "andrew", "character"]
And I want to get every element in the array that starts with a character I type
My problem is when i type "a" the output is "sam", "andrew", and "character".
I want to get the output to only be "andrew". (The string must start from left to right when searching)
You need to filter your array using hasPrefix
var names = ["sam", "andrew", "character"]
var searchString = "a"
let filteredNames = names.filter({ $0.hasPrefix(searchString) })
print(filteredNames)
You must use string.hasPrefix(string)
You can try to use this in Swift 5:
let filteredNames = names.filter{$0.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil}

Making an array with Strings and range of Integer merged

I would like to make a function that generates an array consists of Strings, and integers in range combined as a whole String. For example:
let fruit = "apple"
let numbers = Array(1...10)
let format = ".jpg"
->
["apple1.jpg", "apple2.jpg", "apple3.jpg", ..... "apple10.jpg"]
How can I combine a defined String with range of integers and put them in an array? Apologize for a newbie question. Much appreciated. <3
The simplest solution is you can directly use map on your range.
let array = (1...10).map({ "apple\($0).jpg" })
print(array) //["apple1.jpg", "apple2.jpg", "apple3.jpg", ..... "apple10.jpg"]
Use this:
func mergeStringAndInt(_ prefix: String, intArray: [Int], postfix: String) -> [String] {
return intArray.map {String(format: "%#%d%#", prefix, $0, postfix )}
}
You can do the like -
func resultArray() -> NSMutableArray {
var your_Array = NSMutableArray()
for item in numbers {
let combinedStr = "\(fruit)\(item).\(format)"
your_Array.add(combinedStr)
}
return your_Array
}

How to return an subset of Array of characters?

I am trying to dynamically chop an array of letters but I can't seem to reconvert the result back into a [String]
let letters:String = "abcdefghijklmnopqrstuvwxyz"
let lettersarray = Array(letters.characters)
var targetNum = 14 // Show just the first 14 characters
var resultsArray = [String]()
let resultsSlice = lettersarray.dropLast(lettersarray.count - targetNum) // Returns an Array Slice instead of an Array
let newresultsArray = Array(resultsSlice) // Returns Array<_element> instead of [String]
How do I return a [String] ie ["a","b","c"... eg]
You need to map the Character array back to String
let resultsArray = lettersarray.dropLast(lettersarray.count - targetNum).map{String($0)}
alternatively (credits to Leo Dabus)
let letters = "abcdefghijklmnopqrstuvwxyz"
let targetNum = 14
let resultsArray = letters.characters.prefix(targetNum).map{String($0)}
No need for an array here. It's hard to understand what you're trying to do, but if you just want the first 14 characters of a string, use the prefix method:
let s = String("abcdefghijklmno".characters.prefix(14))
Assuming that you are getting a String and want an array of characters which is a slice of characters from that String, you could use Swift's Half-Open Range Operator found here.
let letters:String = "abcdefghijklmnopqrstuvwxyz"
let lettersArray = Array(letters.characters)
let targetNum = 2
let resultsArray = lettersArray[0..<targetNum]
This will give you an ArraySlice<Character>. If you want an Array<Character> you could do this:
let resultsArray:Array<Character> = Array(lettersArray[0..<targetNum]) // ["a","b"]

Replace just the first character in a string | Swift

I'm trying to replace the just first character of a string. Using this answer, I'm able to replace all current characters with the one I want, but what I really need is to only replace the character if it's at the start of a word.
For example, replace c with t:
Original String: Jack is cool
New Sting: Jack is tool
My Current Code:
let aString: String = "jack is cool"
let toArray: Array = aString.componentsSeparatedByString(" ")
let newString: String = aString.stringByReplacingOccurrencesOfString("c", withString: "t", options: NSStringCompareOptions.LiteralSearch, range: nil)
This would print out as:
"jatk is tool"
I assume I have to do something with the range attribute in the newString.
I would use regex. \\b called word boundary which matches between a word character and a non-word character. You may also use negative lookbehind instead of \\b like (?<!\\S)c
var regex:NSRegularExpression = NSRegularExpression(pattern: "\\bc", options: NSRegularExpressionOptions.CaseInsensitive, error: &ierror)!
var modString = regex.stringByReplacingMatchesInString(myString, options: nil, range: NSMakeRange(0, stringlength), withTemplate: "t")
var aString = 'jack is cool';
var newString = aString.replace('c','t');
var a
var oldString = 'Jack is cool';
var newString = oldString.split(' ');
var x = newString[newString.indexOf('cool')].toString();
x = x.replace('c','t');
newString.splice(newString.indexOf('cool'),1,x);
newString = newString.join(' ').toString();
alert(newString);
You can define your range to start and end at the startIndex to make sure it replaces only occurences at the first character of the string:
let coolString = "Cool"
let newString = coolString.stringByReplacingOccurrencesOfString("C", withString: "T", options: [], range: coolString.startIndex...coolString.startIndex)
You can use String method replace() to replace only the first character of a String
var str = "Cool"
str.replaceRange(str.startIndex...str.startIndex, with: "T")
print(str) // "Tool"
To apply it only to the last word:
var str = "Jack is Cool"
var words = str.componentsSeparatedByString(" ")
if !words.isEmpty {
if !words[words.count-1].isEmpty {
words[words.count-1].replaceRange(str.startIndex...str.startIndex, with: "T")
print( words.last!) // "Tool\n"
}
}
let sentence = words.joinWithSeparator(" ") // "Jack is Tool"

Resources