Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a string with n blank spaces or other repeated character

Tags:

string

ios

swift

I want to make a string with n blank spaces using Swift, but without using a for loop or manually like this:

// string with 5-blank space
var s = "      "
like image 506
Victor Sigler Avatar asked Jan 06 '15 20:01

Victor Sigler


People also ask

How do you make a string of repeating characters?

StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; ++i) { sb. append(c); } String result = sb. toString();

How do you write an n character for a string in Python?

We can easily use the Python join() function to create a string of n characters.

How do you create a string of spaces in Java?

String. format("%5c", ' '); Makes a string with 5 spaces.

How do you put a space in a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').


2 Answers

String already has a repeating:count: initializer just like Array (and other collections that adopt the RangeReplaceableIndexable protocol):

init(repeating repeatedValue: String, count: Int)

So you can just call:

let spaces = String(repeating: " ", count: 5) // -> "     "

Notice that the repeated parameter is a string, not just a character, so you can repeat entire sequences if you want:

let wave = String(repeating: "-=", count: 5) // -> "-=-=-=-=-="

Edit: Changed to Swift 3 syntax and removed discussion of Swift 1 type ambiguity issues. See the edit history if you need to work with old versions.

like image 56
rickster Avatar answered Sep 19 '22 20:09

rickster


In Swift 3:

var s = String(repeating: " ", count: 5)

https://developer.apple.com/reference/swift/string/2427723-init

like image 28
Adam Johns Avatar answered Sep 17 '22 20:09

Adam Johns