我嘗試創建矩陣函數。我想從參數中獲取行數和列數,並像這樣顯示矩陣:使用字符串創建矩陣 - Swift
function stars(rows: Int, columns: Int) -> String {
//I need for loops to create a function body?
}
stars(rows: 5, column: 3)
***
***
***
***
***
我將不勝感激您的幫助!
我嘗試創建矩陣函數。我想從參數中獲取行數和列數,並像這樣顯示矩陣:使用字符串創建矩陣 - Swift
function stars(rows: Int, columns: Int) -> String {
//I need for loops to create a function body?
}
stars(rows: 5, column: 3)
***
***
***
***
***
我將不勝感激您的幫助!
嘗試此代碼:
function stars(rows: Int, columns: Int) -> String {
var str = ""
for i in 0..<rows{
for j in 0..<columns{
str.append("*")
}
str.append("\n")
}
// print(str)
return str
}
是的!非常感謝你:)我非常接近解決方案與我自己的代碼:) – archer
for i in 0..<rows{
for j in 0..<coloumns{
string.append("*")
}
string.append("\n")
}
在操場上試試吧。
String(repeating: "*", count: columns)
創建一個重複某個子串的字符串,例如,String(repeating: "abc", count: 3)
返回abcabcabc
。
repeatElement
+ joined
也是如此,只是它在子串之間放置了分隔符串(在本例中爲\n
)。
func stars(rows: Int, columns: Int) -> String {
let row = String(repeating: "*", count: columns)
return repeatElement(row, count: rows).joined(separator: "\n")
}
是您的大約一個問題[基質](https://en.wikipedia.org/wiki/Matrix_(數學))或約字符串描述的矩形星星的形狀? –
你不會忍受在網上問你的作業問題。 – Alexander
我知道,但有時我需要一些提示來解決問題。感謝您的關注。 – archer