删除字符串

时间:2015-11-02 08:32:37

标签: ios string swift whitespace trim

我在删除字符串开头和结尾的空格时遇到了问题。对于例如我有一个字符串:

\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n

我需要在结尾处开始删除空白 (字符串应如下所示: - Someone will come here?\n- I don't know for sure... 字符串结尾可能有很多变种:" \ r \ n \ r \ n"," \ r \ n"," \ n \ r \ n&n& #34;等等...

感谢。

10 个答案:

答案 0 :(得分:14)

您的字符串不仅包含空格,还包含换行符。

stringByTrimmingCharactersInSetwhitespaceAndNewlineCharacterSet一起使用。

let string = "\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n"
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

在Swift 3中,它已经清理了

let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)

答案 1 :(得分:3)

//here i have used regular expression and replaced white spaces at the start and end
      let stringPassing : NSString? = "hdfjkhsdj hfjksdhf sdf "
      do {
        print("old->\(stringPassing)")
        let pattern : String = "(^\\s+)|(\\s+)$"
        let regex = try NSRegularExpression(pattern: pattern , options: [])
        let newMatched = regex.matchesInString(stringPassing! as String, options: [], range: NSMakeRange(0,stringPassing!.length))
        if(newMatched.count > 0){

          let modifiedString = regex.stringByReplacingMatchesInString(stringPassing! as String, options: [] , range: NSMakeRange(0,stringPassing!.length), withTemplate: "")
              print("new->\(modifiedString)")
        }

    } catch let error as NSError {
        print(error.localizedDescription)
    }

答案 2 :(得分:2)

字符串修剪 Swift 4 +

中的第一个和最后一个空格和换行符
"  2 space  ".trimmingCharacters(in: .whitespacesAndNewlines)

结果: " 2空间"

答案 3 :(得分:1)

您可以使用此扩展程序,只需调用" yourString" .trim()

extension String
{
    func trim() -> String
    {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}

答案 4 :(得分:1)

如果你想从字符串的开头删除空格试试这个代码。

func removeSpace()->String{
    let txt = myString
    var count:Int! = 0
    for i in txt{
        if i  == " "{
            count += 1
        }else{
            if count != 0{
                return String(txt.dropFirst(count))
            }else{
                return txt
            }
        }
    }
    return ""
}

`

答案 5 :(得分:1)

去除字符串开头的所有空格

func removeWhiteSpaces(str:String) -> String{
    var newStr = str
    for i in 0..<str.count{
        let index = str.index(str.startIndex, offsetBy: i)
        print(str[index])
        if str[index] != " "{
            return newStr
        }
        else{
            newStr.remove(at: newStr.startIndex)
        }
    }
    return newStr
}

答案 6 :(得分:0)

在此代码中,用于限制Textfield开头的空白

sed

答案 7 :(得分:0)

在Swift 4中 在任何 String 类型变量上使用它。

extension String {
    func trimWhiteSpaces() -> String {
        let whiteSpaceSet = NSCharacterSet.whitespaces
        return self.trimmingCharacters(in: whiteSpaceSet)
    }
}

然后这样称呼

yourString.trimWhiteSpaces()

答案 8 :(得分:-1)

您可以先从开头删除,然后从结尾删除,如下所示:

while true {
if sentence.characters.first == "\r\n" || sentence.characters.first == "\n" {
    sentence.removeAtIndex(sentence.startIndex)
} else {
    break
}
}

while true {
if sentence.characters.last == "\r\n" || sentence.characters.last == "\n" {
    sentence.removeAtIndex(sentence.endIndex.predecessor())
} else {
    break
}
}

答案 9 :(得分:-1)

let string =“exam ple”

let trimmed = string.replacingOccurrences(of:“(^ \ s +)|(\ s +)$”,with:“”,options:.regularExpression)

print(“&gt;”+ trimmed3 +“&lt;”)

//打印&gt;考试&lt;