I'm trying to append Character to String using "+=", but It doesn't really work.
Once I tried with append method, it works. I just wonder why it is.
The compiler says "string is not identical to Unit8".
let puzzleInput = "great minds think alike"
var puzzleOutput = " "
for character in puzzleInput {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
// error : doesn't work
puzzleOutput += character
//puzzleOutput.append(character)
}
}
println(puzzleOutput)
20140818, Apple updated:
Updated the Concatenating Strings and Characters section to reflect the fact that String and Character values can no longer be combined with the addition operator (+) or addition assignment operator (+=). These operators are now used only with String values. Use the String type’s append method to append a single Character value onto the end of a string.
Document Revision History 2014-08-18
To append a Character to a String in Swift you can do something similar to the following:
var myString: String = "ab"
let myCharacter: Character = "c"
let myStringChar: String = "d"
myString += String(myCharacter) // abc
myString += myStringChar // abcd
Updated version
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default:
puzzleOutput += String(character)
}
}
print(puzzleOutput)
// prints "grtmndsthnklk"
Related
fun printRoom() {
println("Cinema: ")
val rows = 7
val columns = 8
val seats = CharArray(columns) { 'S' }.joinToString { " " }
for (i in 1..rows) {
println("$i" + " " + seats)
}
}
any help will be appreciated. Im sure this is something simple im doing but I can't figure out why this keeps printing commas instead of S's
CharArray.joinToString has these parameters, all of which are optional and have default values:
fun CharArray.joinToString(
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((Char) -> CharSequence)? = null
): String
joinToString allows you to use your own separator, add your own prefix and postfix, have an optional custom limit on the joining, and have a custom string for when that limit is reached, and also optionally transform the Chars into some other String first, before joining them together.
By passing in { " " }, you pass a lambda expression that simply returns the string " ". This corresponds to the transform parameter. Kotlin thinks that you want to transform every Char to the string " " first, and then join the " " together! Because you didn’t pass the separator parameter, the default value of ”, “ is used as the separator, which is why you see a lot of commas.
What you intended on doing is passing " " as the separator parameter. Don't write a lambda:
val seats = CharArray(columns) { 'S' }.joinToString(" ")
You can also be very explicit about this and say:
val seats = CharArray(columns) { 'S' }.joinToString(separator = " ")
If you don't mind a trailing space, repeat also works:
val seats = "S ".repeat(columns)
I cannot find the correct solution or I get an error for something that is very simple in C: how can I convert/move data from a table to string?
The C equivalent of what I am trying to do is:
for (i=0; i <10; i++)
{
string[i] = table[i]
}
I can convert from string to table with :byte(i) but I don't understand how to append a sign in string.
To create a string from all values in a table you can use table.concat, this will concatenate each character in a table.
local myTable = { "h", "e", "l", "l", "o" }
local combinedString = table.concat(myTable)
print(combinedString) -- Outputs hello
Run Code Demo
So given this example:
string = "string"
for char in string:
if char = "a":
# change current character to some other character
elif char = "b"
# change current character to some other character
how can I make it so that the current character of the string is replaced with some other string
("replace()" changes all of the character of the same type
Thanks
i didn't know that string are immutable but i found a workaround for this passing trough a list:
string = 'aa String aa'
string = list(string)
for index in range(len(string)):
if string[index] == 'a':
string[index] = 'c'
string = "".join(string)
maybe other method are faster but if you need to specifically loop though the string this would work fine.
If you don't want to use replace or a regex, you can use this code:
string = "abstring"
new_chars = []
for char in string:
if char == "a":
char = "b"
elif char == "b":
char = "c"
new_chars.append(char)
new_string = "".join(new_chars)
print(string, new_string)
Or you could actually use replace which has a count option:
string = "abstringab"
new_string = string.replace("a", "o", 1)
new_string = new_string.replace("b", "x", 1)
print(new_string)
I'm trying to use inertContentsOf to loop through and find all "\" characters and insert another "\" character in front of it. The problem is I won't always know the index if the character I need to insert.
For example, I know I want to insert "\" at index 3:
myString.insertContentsOf("\\".characters, at: myString.startIndex.advancedBy(3))
How would I do this without knowing the index?
I've tried the following for loops but haven't had any luck.
for words in inputArray {
for char in words {
if char == "\\" {
words.insertContentsOf("\\".characters, at: char)
}
}
}
at: char yells at me for trying to convert a character to an index, which I get but don't know how to fix it.
Edit: For some reason when I try and put it in a function inputArray.map doesn't get called.
func GenerateString(inputArray:[String])->String {
inputArray.map {
$0.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
}
let joiner = "|"
let joinerString = inputArray.joinWithSeparator(joiner)
return ("Result: \(joinerString)")
}
let example = ["hello", "world", "c:\Program File\Example"]
GenerateString(example)
Result:
"Hello|world|c:\Program File\Example"
Use stringByReplacingOccurrencesOfString instead:
words.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
Try stringByReplacingOccurrencesOfString:
var words: String = "c\\Program Files\\Example"
words = words.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
print("Result: \(words)")
// "Result: c\\Program Files\\Example"
or if you want to do this in a array:
let inputArray: [String] = ["hello", "world", "c\\Program Files\\Example"]
inputArray.map {
$0.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
}
print("Result: \(inputArray)")
// "Result: ["hello", "world", "c\\Program Files\\Example"]"
stringByReplacingOccurrencesOfString("\\", withString: "\\\\") line means replace \\ with \\\\ and it's exactly what you want to do. :)
Related Questions: Any way to replace characters on Swift String?
You can call enumerate() on any sequence that is a SequenceType to get the index along with the current item so you can do something like:
for (index, char) in words.enumerate()
Although you should also avoid modifying an array while looping it. Think maybe about having another array where you add normal characters to it, and in the case of \, you add \\
You can do map on your array and use stringByReplacingOccurrencesOfString
let new Array = inputArray.map {
$0.stringByReplacingOccurrencesOfString("\\", withString: "\\\\")
}
How do I remove Optional Character
let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)
println(color) // Optional("Red")
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString)
//http://hahaha.com/ha.php?color=Optional("Red")
I just want output "http://hahaha.com/ha.php?color=Red"
How can I do?
hmm....
Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.
var optionalVariable : String? // This is an optional.
optionalVariable = "I am a programer"
print(optionalVariable) // Optional("I am a programer")
var nonOptionalVariable : String // This is not optional.
nonOptionalVariable = "I am a programer"
print(nonOptionalVariable) // "I am a programer"
//There are different ways to unwrap optional varialble
// 1 (Using if let or if var)
if let optionalVariable1 = optionalVariable {
print(optionalVariable1)
}
// 2 (Using guard let or guard var)
guard let optionalVariable2 = optionalVariable else {
fatalError()
}
print(optionalVariable2)
// 3 (Using default value ?? )
print(optionalVariable ?? "default value") // If variable is empty it will return default value
// 4 (Using force caste !)
print(optionalVariable!) // This is unsafe way and may lead to crash
I looked over this again and i'm simplifying my answer. I think most the answers here are missing the point. You usually want to print whether or not your variable has a value and you also want your program not to crash if it doesn't (so don't use !). Here just do this
print("color: \(color ?? "")")
This will give you blank or the value.
You need to unwrap the optional before you try to use it via string interpolation. The safest way to do that is via optional binding:
if let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex) {
println(color) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color)"
println(imageURLString) // http://hahaha.com/ha.php?color=Red
}
In swift3 you can easily remove optional
if let value = optionalvariable{
//in value you will get non optional value
}
Check for nil and unwrap using "!":
let color = colorChoiceSegmentedControl.titleForSegmentAtIndex(colorChoiceSegmentedControl.selectedSegmentIndex)
println(color) // Optional("Red")
if color != nil {
println(color!) // "Red"
let imageURLString = "http://hahaha.com/ha.php?color=\(color!)"
println(imageURLString)
//"http://hahaha.com/ha.php?color=Red"
}
Besides the solutions mentioned in other answers, if you want to always avoid that Optional text for your whole project, you can add this pod:
pod 'NoOptionalInterpolation'
(https://github.com/T-Pham/NoOptionalInterpolation)
The pod adds an extension to override the string interpolation init method to get rid of the Optional text once for all. It also provides a custom operator * to bring the default behaviour back.
So:
import NoOptionalInterpolation
let a: String? = "string"
"\(a)" // string
"\(a*)" // Optional("string")
Please see this answer https://stackoverflow.com/a/37481627/6390582 for more details.
Try this,
var check:String?="optional String"
print(check!) //optional string. This will result in nil while unwrapping an optional value if value is not initialized or if initialized to nil.
print(check) //Optional("optional string") //nil values are handled in this statement
Go with first if you are confident to have no nil in your variable.
Also, you can use if let or Guard let statement to unwrap optionals without any crash.
if let unwrapperStr = check
{
print(unwrapperStr) //optional String
}
Guard let,
guard let gUnwrap = check else
{
//handle failed unwrap case here
}
print(gUnwrap) //optional String
Simple convert ? to ! fixed my issue:
usernameLabel.text = "\(userInfo?.userName)"
To
usernameLabel.text = "\(userInfo!.userName)"
Although we might have different contexts, the below worked for me.
I wrapped every part of my variable in brackets and then added an exclamation mark outside the right closing bracket.
For example, print(documentData["mileage"]) is changed to:
print((documentData["mileage"])!)
import UIKit
let characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
var a: String = characters.randomElement()!
var b: String = characters.randomElement()!
var c: String = characters.randomElement()!
var d: String = characters.randomElement()!
var e: String = characters.randomElement()!
var f: String = characters.randomElement()!
var password = ("\(a)" + "\(b)" + "\(c)" + "\(d)" + "\(e)" + "\(f)")
print ( password)
when you define any variable as a optional then you need to unwrap that optional value.Convert ? to !
How do I remove optional String Character for Printing in Swift UIkit
From These (Have Optional printing)
print("Collection Cell \(categories[indexPath.row].title) \(indexPath.row)")
To these ( Doesn't have Optional printing)
print("Collection Cell \(categories[indexPath.row].title ?? "default value") \(indexPath.row)")
print("imageURLString = " + imageURLString!)
just use !
You can just put ! and it will work:
print(var1) // optional("something")
print(var1!) // "something"