objective-c NSString 或 NSMutableString 中的字符数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1355691/
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
Count of chars in NSString or NSMutableString?
提问by 4thSpace
I've tried this
我试过这个
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString: myString];
[myCharSet count];
But get a warning that NSCharacterSet may not respond to count. This is for desktop apps and not iPhone, which I think the above code works with.
但是得到一个警告,说 NSCharacterSet 可能不响应计数。这是针对桌面应用程序而不是 iPhone,我认为上面的代码适用于 iPhone。
回答by Matt Ball
I might be missing something here, but what's wrong with simply doing:
我可能在这里遗漏了一些东西,但是简单地做有什么问题:
NSUInteger characterCount = [myString length];
To just get the number of characters in a string, I don't see any reason to mess around with NSCharacterSet.
为了获得字符串中的字符数,我看不出有任何理由来处理 NSCharacterSet。
回答by Kendall Helmstetter Gelner
That should not work on the iPhone either, as NSCharacterSet is not a subclass of NSSet on either platform.
这也不应该在 iPhone 上工作,因为 NSCharacterSet 在任一平台上都不是 NSSet 的子类。
If you really need to get a count why not subclass NSSet, add the value, then have a method that returns that as an NSCharacterSet on demand for use in anything that needs a character set?
如果你真的需要得到一个计数,为什么不继承 NSSet,添加这个值,然后有一个方法将它作为 NSCharacterSet 返回,以便在需要字符集的任何东西中使用?
回答by Saiprabhakar
NSString *string = @"0? ";
__block NSUInteger count = 0;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
count++;
}];
NSLog(@"%ld %ld", (long)count, (long)[string length]);

