swift去掉字符串的空格
时间: 2023-09-14 14:11:54 浏览: 55
要去掉字符串中的空格,可以使用 `trimmingCharacters(in:)` 方法。该方法可以接受一个 `CharacterSet` 类型的参数,用于指定要去掉的字符集合。
以下是一个示例代码:
```
let str = " Hello, world! "
let trimmedStr = str.trimmingCharacters(in: .whitespaces)
print(trimmedStr) // 输出:Hello, world!
```
在上面的示例中,使用 `whitespaces` 字符集合作为参数来去掉字符串两端的空格。如果需要去掉字符串中所有的空格,可以使用 `whitespacesAndNewlines` 字符集合。
```
let str = " Hello, \nworld! "
let trimmedStr = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(trimmedStr) // 输出:Hello,world!
```
相关问题
swift逆序输出字符串
为了在Swift中逆序输出字符串,你可以通过拓展(Extension)给String类添加一个逆序输出字符串的方法。可以使用以下代码实现:
```
extension String {
func reverse() -> String {
var returnString = ""
for i in stride(from: self.count - 1, through: 0, by: -1) {
let index = self.index(self.startIndex, offsetBy: i)
returnString.append(self[index])
}
return returnString
}
}
```
这个方法遍历字符串的每个字符,并将它们按相反的顺序添加到一个新的字符串中。然后返回这个新的字符串。
swift 判断字符串不为空且不为nil
在 Swift 中,可以使用以下方式来判断一个字符串不为空且不为 nil:
```swift
if let str = myString, !str.isEmpty {
// 字符串不为空且不为 nil
} else {
// 字符串为空或为 nil
}
```
其中,`myString` 是要判断的字符串变量。首先使用可选绑定(optional binding)将其解包,如果解包成功并且字符串不为空,则进入第一个分支;否则进入第二个分支。注意,`!` 符号表示逻辑非,即判断字符串不为空的条件。