我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。
当前回答
如果有人从字符串中删除额外的空格,例如= "这是演示文本,请在单词之间删除额外的空格。"
你可以在Swift 4中使用这个函数。
func removeSpace(_ string: String) -> String{
var str: String = String(string[string.startIndex])
for (index,value) in string.enumerated(){
if index > 0{
let indexBefore = string.index(before: String.Index.init(encodedOffset: index))
if value == " " && string[indexBefore] == " "{
}else{
str.append(value)
}
}
}
return str
}
结果是
"This is the demo text remove extra space between the words."
其他回答
你也可以试试这个
let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")
我会使用这个扩展,以灵活和模仿其他集合如何做到这一点:
extension String {
func filter(pred: Character -> Bool) -> String {
var res = String()
for c in self.characters {
if pred(c) {
res.append(c)
}
}
return res
}
}
"this is a String".filter { $0 != Character(" ") } // "thisisaString"
class SpaceRemover
{
func SpaceRemover(str :String)->String
{
var array = Array(str)
var i = array.count
while(array.last == " ")
{
var array1 = [Character]()
for item in 0...i - 1
{
array1.append(array[item])
}
i = i - 1
array = array1
print(array1)
print(array)
}
var arraySecond = array
var j = arraySecond.count
while(arraySecond.first == " ")
{
var array2 = [Character]()
if j > 1
{
for item in 1..<j
{
array2.append(arraySecond[item])
}
}
j = j - 1
arraySecond = array2
print(array2)
print(arraySecond)
}
print(arraySecond)
return String(arraySecond)
}
}
斯威夫特3
你可以简单地使用这个方法删除字符串中的所有普通空格(不考虑所有类型的空白):
let myString = " Hello World ! "
let formattedString = myString.replacingOccurrences(of: " ", with: "")
结果将是:
HelloWorld!
在Swift 4修剪空白
let strFirstName = txtFirstName.text?.trimmingCharacters(in:
CharacterSet.whitespaces)