IT박스

문자열에서 모든 선행 공백을 어떻게 제거해야합니까?

itboxs 2020. 6. 4. 20:09
반응형

문자열에서 모든 선행 공백을 어떻게 제거해야합니까? - 빠른


공백 인 문자열에서 첫 번째 문자를 제거하는 방법이 필요합니다. 문자열의 문자를 잘라내는 데 사용할 수있는 문자열 유형의 메소드 또는 확장을 찾고 있습니다.


선행 및 후행 공백을 제거하려면

let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

스위프트 3 / 스위프트 4 :

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

모든 종류의 공백을 제거하려는 올바른 방법은 ( 이 SO 답변에 따라 ) 다음과 같습니다.

extension String {
    var stringByRemovingWhitespaces: String {
        let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
        return components.joinWithSeparator("")
    }
}

스위프트 3.0+ (3.0, 3.1, 3.2, 4.0)

extension String {
    func removingWhitespaces() -> String {
        return components(separatedBy: .whitespaces).joined()
    }
}

편집하다

이 대답은 모든 공백을 제거하는 것에 관한 질문 일 때 게시되었으며 공백은 언급하도록 편집되었습니다. 선행 공백 만 제거하려면 다음을 사용하십시오.

extension String {
    func removingLeadingSpaces() -> String {
        guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
            return self
        }
        return String(self[index...])
    }
}

이 문자열 확장은 후행 공백뿐만 아니라 문자열에서 모든 공백을 제거합니다 ...

 extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(string: " ", replacement: "")
    }
  }

예:

let string = "The quick brown dog jumps over the foxy lady."
let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady.

스위프트 3

이 방법을 사용하면 문자열에서 모든 일반 공백 을 제거 할 수 있습니다 (모든 유형의 공백은 고려하지 않음).

let myString = " Hello World ! "
let formattedString = myString.replacingOccurrences(of: " ", with: "")

결과는 다음과 같습니다.

HelloWorld!

정규식을 사용할 수도 있습니다.

let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)

Swift 3.0+의 경우 다른 답변을 참조하십시오. 이것은 이제 Swift 2.x의 레거시 답변입니다.

위에서 대답했듯이 첫 번째 문자를 제거하는 데 관심이 있기 때문에 .stringByTrimmingCharactersInSet () 인스턴스 메소드는 훌륭하게 작동합니다.

myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

다음과 같은 방법으로 문자열 경계를 자르기 위해 고유 한 문자 집합을 만들 수도 있습니다.

myString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))

또한 stringByReplacingOccurrencesOfString (target : String, replacement : String) 이라는 하위 문자열을 제거하거나 교체하는 데 사용할 수있는 내장 인스턴스 메소드가 있습니다. 문자열의 어느 곳에서나 발생하는 공백이나 다른 패턴을 제거 할 수 있습니다.

옵션과 범위를 지정할 수 있지만 다음을 수행 할 필요는 없습니다.

myString.stringByReplacingOccurrencesOfString(" ", withString: "")

이것은 문자열에서 반복되는 문자 패턴을 제거하거나 바꾸는 쉬운 방법이며, 매번 전체 문자열을 다시 통과해야하므로 효율성을 떨어 뜨릴 수 있지만 연결될 수 있습니다. 그래서 당신은 이것을 할 수 있습니다 :

 myString.stringByReplacingOccurrencesOfString(" ", withString: "").stringByReplacingOccurrencesOfString(",", withString: "")

...하지만 두 배나 오래 걸릴 것입니다.

Apple 사이트의 .stringByReplacingOccurrencesOfString () 문서

이러한 String 인스턴스 메소드를 체인화하는 것은 단 한 번의 변환에 매우 편리 할 수 ​​있습니다. 예를 들어 짧은 NSData 블로 브를 한 줄에 공백이없는 16 진 문자열로 변환하려는 경우 Swift의 내장 문자열 보간 및 일부 트리밍을 사용하여이 작업을 수행 할 수 있습니다. 교체 :

("\(myNSDataBlob)").stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")).stringByReplacingOccurrencesOfString(" ", withString: "")

대한 신속한 3.0

import Foundation

var str = " Hear me calling"

extension String {
    var stringByRemovingWhitespaces: String {
        return components(separatedBy: .whitespaces).joined()
    }
}

str.stringByRemovingWhitespaces  // Hearmecalling

스위프트 4

정규식을 사용하는 훌륭한 경우 :

" this is    wrong contained teee xt     "
    .replacingOccurrences(of: "^\\s+|\\s+|\\s+$", 
                          with: "", 
                          options: .regularExpression)

// thisiswrongcontainedteeext

이 확장을 사용하여 다른 컬렉션이 수행하는 방식을 유연하고 모방합니다.

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"

If you are wanting to remove spaces from the front (and back) but not the middle, you should use stringByTrimmingCharactersInSet

    let dirtyString   = " First Word "
    let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

If you want to remove spaces from anywhere in the string, then you might want to look at stringByReplacing...


You can try This as well

   let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")

Try functional programming to remove white spaces:

extension String {
  func whiteSpacesRemoved() -> String {
    return self.filter { $0 != Character(" ") }
  }
}

Swift 3 version

  //This function trim only white space:
   func trim() -> String
        {
            return self.trimmingCharacters(in: CharacterSet.whitespaces)
        }
    //This function trim whitespeaces and new line that you enter:
     func trimWhiteSpaceAndNewLine() -> String
        {
            return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        }

extension String {

    var removingWhitespaceAndNewLines: String {
        return removing(.whitespacesAndNewlines)
    }

    func removing(_ forbiddenCharacters: CharacterSet) -> String {
        return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
    }
}

If anybody remove extra space from string e.g = "This is the demo text remove extra space between the words."

You can use this Function in 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
}

and result will be

"This is the demo text remove extra space between the words."

Trimming white spaces in Swift 4

let strFirstName = txtFirstName.text?.trimmingCharacters(in: 
 CharacterSet.whitespaces)

Swift 4, 4.2 and 5

Remove space from front and end only

let str = "  Akbar Code  "
let trimmedString = str.trimmingCharacters(in: .whitespacesAndNewlines)

Remove spaces from every where in the string

let stringWithSpaces = " The Akbar khan code "
let stringWithoutSpaces = stringWithSpaces.replacingOccurrences(of: " ", with: "")

For me, the following line used to remove white space.

let result = String(yourString.filter {![" ", "\t", "\n"].contains($0)})

Yet another answer, sometimes the input string can contain more than one space between words. If you need to standardize to have only 1 space between words, try this (Swift 4/5)

let inputString = "  a very     strange   text !    "
let validInput = inputString.components(separatedBy:.whitespacesAndNewlines).filter { $0.count > 0 }.joined(separator: " ")

print(validInput) // "a very strange text !"

string = string.filter ({!" ".contains($0) })

Swift 3 version of BadmintonCat's answer

extension String {
    func replace(_ string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(" ", replacement: "")
    }
}

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)
    }
}

To remove all spaces from the string:

let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!

참고URL : https://stackoverflow.com/questions/28570973/how-should-i-remove-all-the-leading-spaces-from-a-string-swift

반응형