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

时间:2022-09-07 11:04:13

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)的字符串值是否为“空白”(如果它不是nil)。检查[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.

我仍然很想知道是否有人有其他/首选方式这样做。

3 个解决方案

#1


48  

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

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

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

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

编辑:没有意识到你已经发现了stringByTrimmingCharactersInSet,直到我发布这个。

#2


13  

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.

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

#3


2  

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

#1


48  

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

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

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

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

编辑:没有意识到你已经发现了stringByTrimmingCharactersInSet,直到我发布这个。

#2


13  

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.

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

#3


2  

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