Programing

일련의 공백을 단일 문자로 축소하고 문자열 자르기

lottogame 2020. 7. 11. 10:02
반응형

일련의 공백을 단일 문자로 축소하고 문자열 자르기


다음 예제를 고려하십시오.

"    Hello      this  is a   long       string!   "

나는 그것을 다음으로 변환하고 싶다 :

"Hello this is a long string!"

OS X 10.7 이상 및 iOS 3.2 이상

hfossli에서 제공 하는 기본 정규식 솔루션을 사용하십시오 .

그렇지 않으면

좋아하는 정규식 라이브러리를 사용하거나 다음 Cocoa 네이티브 솔루션을 사용하십시오.

NSString *theString = @"    Hello      this  is a   long       string!   ";

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];

Regex와 NSCharacterSet이 도와 드리겠습니다. 이 솔루션은 앞뒤 공백과 여러 공백을 제거합니다.

NSString *original = @"    Hello      this  is a   long       string!   ";

NSString *squashed = [original stringByReplacingOccurrencesOfString:@"[ ]+"
                                                         withString:@" "
                                                            options:NSRegularExpressionSearch
                                                              range:NSMakeRange(0, original.length)];

NSString *final = [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

로깅 final

"Hello this is a long string!"

가능한 대체 정규식 패턴 :

  • 공간 만 교체하십시오 : [ ]+
  • 공간과 탭을 교체하십시오. [ \\t]+
  • 공백, 탭 및 줄 바꾸기를 바꾸십시오. \\s+

성능 저하

확장, 성능, 코드 수 및 생성 된 개체 수의 용이성으로 인해이 솔루션이 적합합니다.


실제로, 그에 대한 매우 간단한 해결책이 있습니다.

NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)

( 소스 )


정규식을 사용하지만 외부 프레임 워크가 필요하지 않은 경우 :

NSString *theString = @"    Hello      this  is a   long       string!   ";

theString = [theString stringByReplacingOccurrencesOfString:@" +" withString:@" "
                       options:NSRegularExpressionSearch
                       range:NSMakeRange(0, theString.length)];

한 줄 솔루션 :

NSString *whitespaceString = @" String with whitespaces ";

NSString *trimmedString = [whitespaceString
        stringByReplacingOccurrencesOfString:@" " withString:@""];

이것은해야합니다 ...

NSString *s = @"this is    a  string    with lots  of     white space";
NSArray *comps = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSMutableArray *words = [NSMutableArray array];
for(NSString *comp in comps) {
  if([comp length] > 1)) {
    [words addObject:comp];
  }
}

NSString *result = [words componentsJoinedByString:@" "];

정규 표현식의 또 다른 옵션은 RegexKitLite 이며 iPhone 프로젝트에 포함하기가 매우 쉽습니다.

[theString stringByReplacingOccurencesOfRegex:@" +" withString:@" "];

이 시도

NSString *theString = @"    Hello      this  is a   long       string!   ";

while ([theString rangeOfString:@"  "].location != NSNotFound) {
    theString = [theString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
}

다음은 NSString확장 프로그램 의 스 니펫 "self"입니다. NSString인스턴스 어디에 있습니다. 전달하여 하나의 공간으로 연속 된 공백을 축소하는 데 사용할 수 있습니다 [NSCharacterSet whitespaceAndNewlineCharacterSet]' '두 개의 인수에.

- (NSString *) stringCollapsingCharacterSet: (NSCharacterSet *) characterSet toCharacter: (unichar) ch {
int fullLength = [self length];
int length = 0;
unichar *newString = malloc(sizeof(unichar) * (fullLength + 1));

BOOL isInCharset = NO;
for (int i = 0; i < fullLength; i++) {
    unichar thisChar = [self characterAtIndex: i];

    if ([characterSet characterIsMember: thisChar]) {
        isInCharset = YES;
    }
    else {
        if (isInCharset) {
            newString[length++] = ch;
        }

        newString[length++] = thisChar;
        isInCharset = NO;
    }
}

newString[length] = '\0';

NSString *result = [NSString stringWithCharacters: newString length: length];

free(newString);

return result;
}

대체 솔루션 : OgreKit (Cocoa 정규식 라이브러리) 사본을 받으십시오.

전체 기능은 다음과 같습니다.

NSString *theStringTrimmed =
   [theString stringByTrimmingCharactersInSet:
        [NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression  *regex =
    [OGRegularExpression regularExpressionWithString:@"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:@" "]);

짧고 달다.

If you're after the fastest solution, a carefully constructed series of instructions using NSScanner would probably work best but that'd only be necessary if you plan to process huge (many megabytes) blocks of text.


according from @Mathieu Godart is best answer, but some line is missing , all answers just reduce space between words , but when if have tabs or have tab in place space , like this: " this is text \t , and\tTab between , so on " in three line code we will : the string we want reduce white spaces

NSString * str_aLine = @"    this is text \t , and\tTab between      , so on    ";
// replace tabs to space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
// reduce spaces to one space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@" +" withString:@" "
                                                    options:NSRegularExpressionSearch
                                                      range:NSMakeRange(0, str_aLine.length)];
// trim begin and end from white spaces
str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

the result is

"this is text , and Tab between , so on"

without replacing tab the resul will be:

"this is text    , and  Tab between , so on"

You can also use a simple while argument. There is no RegEx magic in there, so maybe it is easier to understand and alter in the future:

while([yourNSStringObject replaceOccurrencesOfString:@"  "
                         withString:@" "
                         options:0
                         range:NSMakeRange(0, [yourNSStringObject length])] > 0);

Following two regular expressions would work depending on the requirements

  1. @" +" for matching white spaces and tabs
  2. @"\\s{2,}" for matching white spaces, tabs and line breaks

Then apply nsstring's instance method stringByReplacingOccurrencesOfString:withString:options:range: to replace them with a single white space.

e.g.

[string stringByReplacingOccurrencesOfString:regex withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];

Note: I did not use 'RegexKitLite' library for the above functionality for iOS 5.x and above.

참고URL : https://stackoverflow.com/questions/758212/collapse-sequences-of-white-space-into-a-single-character-and-trim-string

반응형