IT박스

NSString에서 모든 공백 제거

itboxs 2020. 6. 29. 08:14
반응형

NSString에서 모든 공백 제거


에서 공백을 제거 NSString하려고 시도했지만 시도한 방법 중 아무것도 작동하지 않았습니다.

나는 "this is a test"있고 싶어요 "thisisatest".

whitespaceCharacterSet공백을 제거 해야하는을 사용했습니다 .

NSString *search = [searchbar.text stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

그러나 공백이있는 동일한 문자열을 계속 얻었습니다. 어떤 아이디어?


stringByTrimmingCharactersInSet 문자열의 시작과 끝에서 문자 만 제거하고 중간 문자는 제거하지 않습니다.

1) 문자열에서 주어진 문자 (예 : 공백 문자) 만 제거 해야하는 경우 다음을 사용하십시오.

[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]

2) 문자 집합 (즉, 공백 문자뿐만 아니라 공백, 탭, 깨지지 않는 공백 등의 공백 문자 ) 을 실제로 제거 해야하는 경우 문자열을 분할 whitespaceCharacterSet한 다음 단어를 한 문자열로 다시 결합 할 수 있습니다 :

NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:@""];

이 마지막 솔루션은 공백뿐만 아니라 모든 공백 문자를 처리 할 수 ​​있다는 장점이 있지만 stringByReplacingOccurrencesOfString:withString:. 따라서 실제로 공백 문자 만 제거해야하고 일반 공백 문자 이외의 다른 공백 문자가없는 경우 첫 번째 방법을 사용하십시오.


다음과 같이 정규식을 사용하는 것이 좋습니다.

NSString *myString = @"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s"
                                     withString:@""
                                        options:NSRegularExpressionSearch
                                          range:NSMakeRange(0, [myStringlength])];
 //myNewString will be @"thisisatest"

NSString에서 자신을 범주화하여 인생을 더욱 쉽게 만들 수 있습니다.

- (NSString *) removeAllWhitespace
{
    return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@""
                                              options:NSRegularExpressionSearch
                                                range:NSMakeRange(0, [self length])];

}

여기에 단위 테스트 방법이 있습니다.

- (void) testRemoveAllWhitespace
{
    NSString *testResult = nil;

    NSArray *testStringsArray        = @[@""
                                         ,@"    "
                                         ,@"  basicTest    "
                                         ,@"  another Test \n"
                                         ,@"a b c d e f g"
                                         ,@"\n\tA\t\t \t \nB    \f  C \t  ,d,\ve   F\r\r\r"
                                         ,@"  landscape, portrait,     ,,,up_side-down   ;asdf;  lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & *  * ()+  +   "
                                         ];

    NSArray *expectedResultsArray   = @[@""
                                        ,@""
                                        ,@"basicTest"
                                        ,@"anotherTest"
                                        ,@"abcdefg"
                                        ,@"ABC,d,eF"
                                        ,@"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!@@##$$%^^&**()++"
                                        ];

    for (int i=0; i < [testStringsArray count]; i++)
    {
        testResult = [testStringsArray[i] removeAllWhitespace];
        STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"",
                     testStringsArray[i], expectedResultsArray[i], testResult);
    }
}

사용하기 쉬운 작업 stringByReplacingOccurrencesOfString

NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];

This may help you if you are experiencing \u00a0 in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it.

NSString* yourString = [yourString stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];

When yourString was the current phone number.


stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end

Use

[YourString stringByTrimmingCharactersInSet:[NSCharacterSet  whitespaceAndNewlineCharacterSet]]

- (NSString *)removeWhitespaces {
  return [[self componentsSeparatedByCharactersInSet:
                    [NSCharacterSet whitespaceCharacterSet]]
      componentsJoinedByString:@""];
}

This for me is the best way SWIFT

        let myString = "  ciao   \n              ciao     "
        var finalString = myString as NSString

        for character in myString{
        if character == " "{

            finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")

        }else{
            finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")

        }

    }
     println(finalString)

and the result is : ciaociao

But the trick is this!

 extension String {

    var NoWhiteSpace : String {

    var miaStringa = self as NSString

    if miaStringa.containsString(" "){

      miaStringa =  miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
    }
        return miaStringa as String

    }
}

let myString = "Ciao   Ciao       Ciao".NoWhiteSpace  //CiaoCiaoCiao

Use below marco and remove the space.

#define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

in other file call TRIM :

    NSString *strEmail;
    strEmail = TRIM(@"     this is the test.");

May it will help you...


That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use

xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];

It will replace empty space with no space and empty field is taken care of by below method:

searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

I strongly suggest placing this somewhere in your project:

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

    func trim(withSet: NSCharacterSet) -> String {
        return self.stringByTrimmingCharactersInSet(withSet)
    }
}

참고URL : https://stackoverflow.com/questions/7628470/remove-all-whitespaces-from-nsstring

반응형