从Cocoa Touch中的字符串修剪空格的最好方法是什么? [英] What's the best way to trim whitespace from a string in Cocoa Touch?
问题描述
我想要确定来自用户输入(UITextField)的字符串值是否为空白,如果它不是nil。检查 [textField.text isEqualToString:]
是不够的,因为我想避免任何空白/空格输入(比如说几个空格字符)。
似乎有一个良好的解决方案,我的特定问题的指示在此StOv帖子。
像这样,但我怀疑有(或应该)是一个更好的方法:
NSString * strResult;
NSScanner * scanner = [NSScanner scannerWithString:textField.text];
BOOL hasValidChars = [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
intoString:& strResult];
//如果hasValidChars == YES,我们有非空白字符集合到strResult中
这显然只适用于我的特定情况,即使那样,如果第一个字符是一个空格,但是我想要的数据,它会失败。所以,我意识到我有点被宠坏了Ruby,但是必须有一个尝试和真正的成语修剪字符串在Cocoa。
Aaa和答案已经在那里,我的道歉:
NSString的 -stringByTrimmingCharactersInSet:
p>
返回通过从接收者的两端移除
所创建的新字符串
给定的
中包含的字符字符集。
我仍然很好奇,如果有人有其他/首选的方法。
你使用的是whitespaceAndNewlineCharacterSet,很好。但是,而不是使用scanUpToCharactersFromSet,为什么不使用stringByTrimmingCharactersInSet?像这样...
strResult = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
编辑:没有意识到你已经找到stringByTrimmingCharactersInSet,直到我发布了这个。
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).
There does seem to be an indication of a good solution for my particular problem in this StOv post.
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.
Aaaand the answer is already out there, my apologies:
NSString's -stringByTrimmingCharactersInSet:
would do it:
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.
You're using whitespaceAndNewlineCharacterSet, good. But instead of using scanUpToCharactersFromSet, why not use stringByTrimmingCharactersInSet? Something like this...
strResult = [strResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
EDIT: Didn't realize you already found stringByTrimmingCharactersInSet until after I posted this.
这篇关于从Cocoa Touch中的字符串修剪空格的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!