objective-c 在 Cocoa Touch 中从字符串中修剪空格的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/474270/
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-09-03 21:03:43  来源:igfitidea点击:

What's the best way to trim whitespace from a string in Cocoa Touch?

objective-cstringcocoa-touchwhitespace

提问by Billy Gray

I'm looking to determine whether a string value from a user input (UITextField) is "blank" if it's not nil. Checking if [textField.text isEqualToString:""]isn't quite enough because I want to avoid any blank/whitespace input (like say a few space characters).

我正在寻找确定来自用户输入 (UITextField) 的字符串值是否为“空白”(如果它不是零)。检查是否[textField.text isEqualToString:""]还不够,因为我想避免任何空白/空白输入(比如几个空格字符)。

There does seem to be an indication of a good solution for my particular problem in this StOv post.

在这篇 StOv 帖子中,似乎确实为我的特定问题提供了一个很好的解决方案。

Basically it goes something like this, but I suspect there has to (or ought to) be a better way:

基本上它是这样的,但我怀疑必须(或应该)有更好的方法:

NSString *strResult;
NSScanner* scanner = [NSScanner scannerWithString:textField.text];
BOOL hasValidChars = [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] 
                                             intoString:&strResult];

// if hasValidChars == YES, we've got nonwhite space chars collected into strResult

This clearly only works for my particular circumstance, and even then it would fail if the first character was a space but the data I wanted followed. So, I realize I've been a little spoiled by Ruby, but there must be a tried and true idiom for trimming strings in Cocoa.

这显然仅适用于我的特定情况,即使第一个字符是空格但我想要的数据紧随其后,它也会失败。所以,我意识到我有点被 Ruby 宠坏了,但是在 Cocoa 中修剪字符串肯定有一个久经考验的成语。

Aaaand the answer is already out there, my apologies:

Aaaand答案已经在那里了,我很抱歉:

NSString's -stringByTrimmingCharactersInSet:would do it:

NSString-stringByTrimmingCharactersInSet:会这样做:

Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

返回通过从给定字符集中包含的接收器字符的两端删除而制成的新字符串。

I'm still curious to hear if anybody has other/preferred ways of doing this.

我仍然很想知道是否有人有其他/首选的方法来做到这一点。

回答by Matt Flowers

You're using whitespaceAndNewlineCharacterSet, good. But instead of using scanUpToCharactersFromSet, why not use stringByTrimmingCharactersInSet? Something like this...

你正在使用 whitespaceAndNewlineCharacterSet,很好。但是为什么不使用 scanUpToCharactersFromSet,为什么不使用 stringByTrimmingCharactersInSet?像这样的东西...

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

EDIT: Didn't realize you already found stringByTrimmingCharactersInSet until after I posted this.

编辑:直到我发布此内容后,您才意识到您已经找到了 stringByTrimmingCharactersInSet。

回答by McShashi

What you are looking for is

你要找的是

[string stringByReplacingOccurrencesOfString:@" " withString:@""].

[string stringByReplacingOccurrencesOfString:@" " withString:@""].

Deleting white space in the middle of a string is not called 'trimming'.

删除字符串中间的空白不称为“修剪”。

Trimming by definition works from the edges.

根据定义修剪是从边缘开始的。

回答by NoodleOfDeath

To make this easier on yourself and instead of making a subclass, you can modify existing Apple classes and do something like

为了让自己更轻松,而不是创建子类,您可以修改现有的 Apple 类并执行类似的操作

//
// NSString+MyExtensions.h
//

@interface NSString (MyExtensions)

- (NSString *)trimmed;

@end

and the implementation

和实施

//
// NSString+MyExtensions.m
//

#import "NSString+MyExtensions.h"

@implementation NSString (MyExtensions)

- (NSString *)trimmed {
     return [self stringByTrimmingCharactersInSet:
             [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

@end

So now anywhere in your app that you use an NSString,
you can now call [@" hello world " trimmed]like below

所以,现在在你的应用程序的任何地方,你使用NSString
你现在可以调用[@" hello world " trimmed]像下面

//
// ViewController.m
//

#import "NSString+MyExtensions.h"

@implementation ViewController

- (void)viewDidLoad {

    NSString *string = @"      This is a string    ";

    NSLog(@"The original string: %@ \n The trimmed string: %@\n\n",
          string,
          [string trimmed]);

    string = @"                 ";

    if([string trimmed].length == 0)
        NSLog(@"%@", @"String is empty! :O");

}

@end

Which would print out

哪个会打印出来

The original string:       This is a string    
The trimmed string: This is a string

String is empty! :O