String index in Swift 2.0: How can I work around indexing a string? - swift

I am trying to get the contents of a string:
var oldString = "hi this \t is my \t string"
oldString = String(oldString.componentsSeparatedByString("\t"))
print(oldString[1])
I get the ERROR : " 'subscript' is unavailable:cannot subscript String
with an Int..."
How would I access a string that is contained in another string?
The only way I have come up with is to get character by character using:
for index in content.characters.indices{
print(String(oldString[index]))
}
The code above results in:
h,
i,
t,
h,
..
I need:
hi this,
is my,
string
Thank you in advance!

You should read the error message and figure out where does the error message come from.
Your String(oldString.componentsSeparatedByString("\t")) gives you a String not [String].
What you need to do is assigning oldString.componentsSeparatedByString("\t") to an array:
let stringArray = oldString.componentsSeparatedByString("\t")
for str in stringArray {
print(str)
}

In swift you can extend any type and add overloads for different operations. In the example below we've created an extension that allows you to subscript String returning each word and get an array from your string.
Simply paste this into a playground to test:
extension String {
func array() -> [String] {
return self.componentsSeparatedByString("\t")
}
subscript (i: Int) -> String {
return self.componentsSeparatedByString("\t")[i]
}
}
Once you've added your extension, you can use it throughout your application like so:
var str = "hi this \t is my \t string"
print(str[0]) //prints hi this
for i in str.array() {
print(i)
}
prints:
hi this
is my
string

var oldString = "hi this \t is my \t string"
let stringArray = oldString.componentsSeparatedByString("\t")
//In case you also need the index while iterating
for (index, value) in stringArray.enumerate(){
print("index is \(index) and string is \(value)")
}
for str in stringArray{
print(str)
}
Output will be as follows
index is 0 and string is hi this
index is 1 and string is is my
index is 2 and string is string
hi this
is my
string

Related

Cannot convert value of type Substring to expected argument type String - Swift 4

Trying to get substring of String and append it to array of Strings:
var stringToSplit = "TEST TEXT"
var s = [String]()
let subStr = anotherString[0 ..< 6]
s.append(subStr) // <---- HERE I GET THE ERROR
As #Leo Dabus mentioned, you need to initialize a new String with your substring:
Change:
s.append(subStr)
To:
s.append(String(subStr))
my two cents for serro in different context.
I was trying to get an array of "String" splitting a string.
"split" gives back "Substring", for efficiency reason (as per Swift.org litre).
So I ended up doing:
let buffer = "one,two,three"
let rows = buffer.split(separator:",")
let realStrings = rows.map { subString -> String in
return String(subString)
}
print(realStrings)
Ape can help someone else.

Swift: cannot subscript a value of type aka 'Array<Character>'

I'm trying to access to one character in string but I'm getting the following error:
error: cannot subscript a value of type 'Array<_Element>' (aka 'Array<Character>')
finalString = characters [ 5 ]
Here is my code:
// my string:
var str = "Hello, playground"
// I'm converting the string into array of characters:
let characters = Array(str.characters)
// String where I want to transfer the character:
var finalString:String
finalString = characters [ 5 ]
But in the last line of code is where I get the error. Any of you knows what I'm doing wrong or a way around this error.
I'll really appreciate your help
You have an array of Characters, you need to turn that back into a string to get what you want. Try this:
// my string:
var str = "Hello, playground"
// I'm converting the string into array of characters:
let characters = Array(str.characters)
// String where I want to transfer the character:
var finalString = String(characters[ 5 ])

How to convert a character to string in swift?

I wanted to perform a if condition for each character in a string, the string consists of digits and alphabets so I want to separate digits by using if condition, so how to extract each character and add it to another string
I've tried to convert using
NSString
But even then It didn't work
so is there anything like
toInt()
You can cast directly to swift String:
let c : Character = "c"
let str = String(c)
You can not access a character at a index of string with str[index], you have to access by a Range. If you want to access this way, add a subscript extension to String:
extension String {
subscript (index: Int) -> Character {
return self[advance(self.startIndex, index)]
}
}
then, you can call:
let myString = "abcdef"
let c: Character = myString[1] //return 'b'

How to append a character to a string in Swift?

This used to work in Xcode 6: Beta 5. Now I'm getting a compilation error in Beta 6.
for aCharacter: Character in aString {
var str: String = ""
var newStr: String = str.append(aCharacter) // ERROR
...
}
Error: Cannot invoke append with an argument of type Character
Update for the moving target that is Swift:
Swift no longer has a + operator that can take a String and an array of characters. (There is a string method appendContentsOf() that can be used for this purpose).
The best way of doing this now is Martin R’s answer in a comment below:
var newStr:String = str + String(aCharacter)
Original answer:
This changed in Beta 6. Check the release notes.I'm still downloading it, but try using:
var newStr:String = str + [aCharacter]
This also works
var newStr:String = str + String(aCharacter)
append append(c: Character) IS the right method but your code has two other problems.
The first is that to iterate over the characters of a string you must access the String.characters property.
The second is that the append method doesn't return anything so you should remove the newStr.
The code then looks like this:
for aCharacter : Character in aString.characters {
var str:String = ""
str.append(aCharacter)
// ... do other stuff
}
Another possible option is
var s: String = ""
var c: Character = "c"
s += "\(c)"
According to Swift 4 Documentation ,
You can append a Character value to a String variable with the String type’s append() method:
var welcome = "hello there"
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
var stringName: String = "samontro"
var characterNameLast: Character = "n"
stringName += String(characterNameLast) // You get your name "samontron"
I had to get initials from first and last names, and join them together. Using bits and pieces of the above answers, this worked for me:
var initial: String = ""
if !givenName.isEmpty {
let char = (givenName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
if !familyName.isEmpty {
let char = (familyName as NSString).substring(with: NSMakeRange(0, 1))
let str = String(char)
initial.append(str)
}
for those looking for swift 5, you can do interpolation.
var content = "some random string"
content = "\(content)!!"
print(content) // Output: some random string!!
let original:String = "Hello"
var firstCha = original[original.startIndex...original.startIndex]
var str = "123456789"
let x = (str as NSString).substringWithRange(NSMakeRange(0, 4))
var appendString1 = "\(firstCha)\(x)" as String!
// final name
var namestr = "yogesh"
var appendString2 = "\(namestr) (\(appendString1))" as String!*

What's the best way to convert String into [Character] in Swift?

I would like to run a filter on a string. My first attempt failed as string is not automagically converted to Character[].
var s: String = "abc"
s.filter { $0 != "b" }
If I clumsily convert the String to Character[] with following code, it works as expected. But surely there has to be a neater way?
var cs:Character[] = []
for c in s {
cs = cs + [c]
}
cs = cs.filter { $0 != "b" }
println(cs)
String conforms to the CollectionType protocol, so you can pass it directly to the function forms of map and filter without converting it at all:
let cs = filter(s) { $0 != "f" }
cs here is an Array of Characters. You can turn it into a String by using the String(seq:) initializer, which constructs a String from any SequenceType of Characters. (SequenceType is a protocol that all lists conform to; for loops use them, among many other things.)
let filteredString = String(seq: cs)
Of course, you can just as easily put those two things in one statement:
let filteredString = String(seq: filter(s) { $0 != "f" })
Or, if you want to make a convenience filter method like the one on Array, you can use an extension:
extension String {
func filter(includeElement: Character -> Bool) -> String {
return String(seq: Swift.filter(self, includeElement))
}
}
(You write it "Swift.filter" so the compiler doesn't think you're trying to recursively call the filter method you're currently writing.)
As long as we're hiding how the filtering is performed, we might as well use a lazy filter, which should avoid constructing the temporary array at all:
extension String {
func filter(includeElement: Character -> Bool) -> String {
return String(seq: lazy(self).filter(includeElement))
}
}
I don't know of a built in way to do it, but you could write your own filter method for String:
extension String {
func filter(f: (Character) -> Bool) -> String {
var ret = ""
for character in self {
if (f(character)) {
ret += character
}
}
return ret
}
}
If you don't want to use an extension you could do this:
Array(s).filter({ $0 != "b" }).reduce("", combine: +)
You can use this syntax:
var chars = Character[]("abc")
I'm not 100% sure if the result is an array of Characters or not but works for my use case.
var str = "abc"
var chars = Character[](str)
var result = chars.map { char in "char is \(char)" }
result
The easiest way to convert a char to string is using the backslash (), for example I have a function to reverse a string, like so.
var identityNumber:String = id
for char in identityNumber{
reversedString = "\(char)" + reversedString
}