ios 将空白序列折叠为单个字符并修剪字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/758212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:49:30  来源:igfitidea点击:

Collapse sequences of white space into a single character and trim string

objective-ciosnsstring

提问by Georg Sch?lly

Consider the following example:

考虑以下示例:

"    Hello      this  is a   long       string!   "

I want to convert that to:

我想将其转换为:

"Hello this is a long string!"

回答by Georg Sch?lly

OS X 10.7+ and iOS 3.2+

OS X 10.7+ 和 iOS 3.2+

Use the native regexp solutionprovided by hfossli.

使用hfossli 提供的原生正则表达式解决方案

Otherwise

除此以外

Either use your favorite regexp library or use the following Cocoa-native solution:

要么使用您最喜欢的正则表达式库,要么使用以下 Cocoa-native 解决方案:

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:@" "];

回答by hfossli

Regex and NSCharacterSet is here to help you. This solution trims leading and trailing whitespace as well as multiple whitespaces.

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]];

Logging finalgives

记录final给出

"Hello this is a long string!"

Possible alternative regex patterns:

可能的替代正则表达式模式:

  • Replace only space: [ ]+
  • Replace space and tabs: [ \\t]+
  • Replace space, tabs and newlines: \\s+
  • 只替换空格: [ ]+
  • 替换空格和制表符: [ \\t]+
  • 替换空格、制表符和换行符: \\s+

Performance rundown

性能下降

Ease of extension, performance, number lines of code and the number of objects created makes this solution appropriate.

易于扩展、性能、代码行数和创建的对象数量使此解决方案合适。

回答by arikfr

Actually, there's a very simple solution to that:

实际上,有一个非常简单的解决方案:

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

(Source)

来源

回答by MonsieurDart

With a regex, but without the need for any external framework:

使用正则表达式,但不需要任何外部框架:

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

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

回答by TwoBeerGuy

A one line solution:

一行解决方案:

NSString *whitespaceString = @" String with whitespaces ";

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

回答by Barry Wark

This should do it...

这个应该可以...

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:@" "];

回答by Daniel Dickison

Another option for regex is RegexKitLite, which is very easy to embed in an iPhone project:

regex 的另一个选项是RegexKitLite,它很容易嵌入到 iPhone 项目中:

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

回答by dmercredi

Here's a snippet from an NSStringextension, where "self"is the NSStringinstance. It can be used to collapse contiguous whitespace into a single space by passing in [NSCharacterSet whitespaceAndNewlineCharacterSet]and ' 'to the two arguments.

下面是一个片段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] = '
NSString *theString = @"    Hello      this  is a   long       string!   ";

while ([theString rangeOfString:@"  "].location != NSNotFound) {
    theString = [theString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
}
'; NSString *result = [NSString stringWithCharacters: newString length: length]; free(newString); return result; }

回答by sinh99

Try This

尝试这个

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

回答by apalvai

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
  1. @" +" 用于匹配空格和制表符
  2. @"\\s{2,}" 用于匹配空格、制表符和换行符

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

然后应用 nsstring 的实例方法stringByReplacingOccurrencesOfString:withString:options:range:将它们替换为单个空格。

e.g.

例如

##代码##

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

注意:对于 iOS 5.x 及更高版本的上述功能,我没有使用“RegexKitLite”库。