删除字符串开头和结尾的空格
removing white spaces at beginning and end of string
我在删除字符串开头和结尾的空格时遇到了问题。例如我有一个像这样的字符串:
\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”等等...
谢谢。
您可以先从开头删除,然后从结尾删除,如下所示:
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
}
}
您的字符串不仅包含空格,还包含换行符。
将 stringByTrimmingCharactersInSet
与 whitespaceAndNewlineCharacterSet
结合使用。
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)
您可以使用此扩展程序,只需调用 "yourString".trim()
extension String
{
func trim() -> String
{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
//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)
}
字符串修剪第一个和最后一个白色spaces 和 Swift 中的换行符 4+
" 2 space ".trimmingCharacters(in: .whitespacesAndNewlines)
结果:
“2 space”
let string = " example "
let trimmed = string.replacingOccurrences(of: "(^\s+)|(\s+)$", with: "", options: .regularExpression)
print(">" + trimmed3 + "<")
// 打印 >示例<
在此代码中限制文本字段以白色开头space
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.count)! == 0 && string == " " {
return false
}
else{
return true
}
}
在Swift4
在任何 String 类型变量上使用它。
extension String {
func trimWhiteSpaces() -> String {
let whiteSpaceSet = NSCharacterSet.whitespaces
return self.trimmingCharacters(in: whiteSpaceSet)
}
}
并这样称呼它
yourString.trimWhiteSpaces()
如果你想从字符串的开头删除空格试试这个代码。
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 ""
}
`
删除字符串开头的所有空格
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
}
我在删除字符串开头和结尾的空格时遇到了问题。例如我有一个像这样的字符串:
\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”等等...
谢谢。
您可以先从开头删除,然后从结尾删除,如下所示:
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
}
}
您的字符串不仅包含空格,还包含换行符。
将 stringByTrimmingCharactersInSet
与 whitespaceAndNewlineCharacterSet
结合使用。
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)
您可以使用此扩展程序,只需调用 "yourString".trim()
extension String
{
func trim() -> String
{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
//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)
}
字符串修剪第一个和最后一个白色spaces 和 Swift 中的换行符 4+
" 2 space ".trimmingCharacters(in: .whitespacesAndNewlines)
结果: “2 space”
let string = " example "
let trimmed = string.replacingOccurrences(of: "(^\s+)|(\s+)$", with: "", options: .regularExpression)
print(">" + trimmed3 + "<")
// 打印 >示例<
在此代码中限制文本字段以白色开头space
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.text?.count)! == 0 && string == " " {
return false
}
else{
return true
}
}
在Swift4 在任何 String 类型变量上使用它。
extension String {
func trimWhiteSpaces() -> String {
let whiteSpaceSet = NSCharacterSet.whitespaces
return self.trimmingCharacters(in: whiteSpaceSet)
}
}
并这样称呼它
yourString.trimWhiteSpaces()
如果你想从字符串的开头删除空格试试这个代码。
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 ""
}
`
删除字符串开头的所有空格
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
}