C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For complex string mutations, building up a new string based on characters is sometimes easiest.
For: We use a for-in loop to iterate over the three characters in the Character array.
Then: We add each character 3 times to the result string. We finally print the string to the console.
PrintSwift program that uses append, adds Characters to string
let chars: [Character] = ["A", "B", "C"]
var result = String()
// Loop over all Characters in the array.
for char in chars {
for var i in 0..<3 {
// Append a Character to the string.
result.append(char)
}
}
// Write the result String.
print(result)
Output
AAABBBCCC
Swift program that appends strings
var result = "cat"
// The append method can append a string.
result.append(" and dog")
print(result)
Output
cat and dog
Here: We use reserveCapacity with an argument of 100, which accommodates 100 ASCII characters.
Swift program that uses reserveCapacity
// Use reserveCapacity to ensure enough memory.
// ... This reduces resizing.
var pattern = String()
pattern.reserveCapacity(100)
// Add characters to string.
for i in 0..<100 {
pattern += "a"
}
// Print first 20 characters of the string.
print(pattern[pattern.startIndex..<pattern.index(pattern.startIndex, offsetBy: 20)])
Output
aaaaaaaaaaaaaaaaaaaa