如何去掉字符串前空白符?空格符,TAB制表符,回车ASCII码各为多少

 我来答
乐跑小子
推荐于2016-07-22 · TA获得超过1.5万个赞
知道大有可为答主
回答量:1.1万
采纳率:7%
帮助的人:4726万
展开全部
在objective-c中,如何去掉一个string 的前后的空格字符或某个特定字符呢?
如@ “ abc 123 ”字符串前后有空格,该如何去掉?
使用nsstring 的实例方法stringByTrimmingCharactersInSet :可以解决该问题。
方法如下:
C代码 收藏代码
[@" abc 123 " stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

NSString 中该方法说明如下:
stringByTrimmingCharactersInSet:
Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
Parameters
set
A character set containing the characters to remove from the receiver. set must not be nil .
Return Value
A new string made by removing from both ends of the receiver characters contained in set . If the receiver is composed entirely of characters from set , the empty string is returned.

这是典型的其他语言中trim 方法。我要问的是,如何去掉最左边的空格?又该如何去掉最右边的空格?
在NSString 的类中没有提供实现这类需求的方法,我们只能手工去添加这些方法。

C代码 收藏代码
@interface NSString (TrimmingAdditions)
- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet ;
- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet ;
@end

@implementation NSString (TrimmingAdditions)

- (NSString *)stringByTrimmingLeftCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];

for (location; location < length; location++) {
if (![characterSet characterIsMember:charBuffer[location]]) {
break;
}
}

return [self substringWithRange:NSMakeRange(location, length - location)];
}

- (NSString *)stringByTrimmingRightCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger location = 0;
NSUInteger length = [self length];
unichar charBuffer[length];
[self getCharacters:charBuffer];

for (length; length > 0; length--) {
if (![characterSet characterIsMember:charBuffer[length - 1]]) {
break;
}
}

return [self substringWithRange:NSMakeRange(location, length - location)];
}

@end
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式