Objectvie-C之 NSString 处理技巧<一>:分割字符串

一、带节点的字符串,如@"<p>讨厌的节点<br/></p>"我们只想要中间的中文

处理方法一:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
NSString *string1 = @ "<p>讨厌的节点<br/></p>" ;
 
/*此处将不想要的字符全部放进characterSet1中,不需另外加逗号或空格之类的,除非字符串中有你想要去除的空格,此处< p /等都是单独存在,不作为整个字符*/
 
NSCharacterSet *characterSet1 = [NSCharacterSet characterSetWithCharactersInString:@ "<p/brh>" ];
 
// 将string1按characterSet1中的元素分割成数组
 
NSArray *array1 = [string1 componentsSeparatedByCharactersInSet:characterSet1];
 
NSLog(@ "array = %@" ,array1);
 
for (NSString *string1 in array1)
{
     if ([string1 length]>0) {
         
         // 此处string即为中文字符串
 
         NSLog(@ "string = %@" ,string1);
     }
}

打印结果:  2013-05-31 10:55:34.017 string[17634:303] 

array = (
    "",
    "",
    "",
    "\U8ba8\U538c\U7684\U8282\U70b9",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
)
2013-05-31 10:55:34.049 string[17634:303] 
string = 讨厌的节点


二、带空格的字符串,如

@"hello world"去掉空格

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
NSString *string2 = @ "hello world" ;
 
/*处理空格*/
 
NSCharacterSet *characterSet2 = [NSCharacterSet whitespaceCharacterSet];
 
// 将string1按characterSet1中的元素分割成数组
NSArray *array2 = [string2 componentsSeparatedByCharactersInSet:characterSet2];
 
NSLog(@ "\narray = %@" ,array2);
 
// 用来存放处理后的字符串
NSMutableString *newString1 = [NSMutableString string];
 
for (NSString *string in array1)
{
     [newString1 appendString:string];
}
NSLog(@ "newString = %@" , newString1);

打印结果:

2013-05-31 11:02:49.656 string[17889:303] 
array = (
    hello,
    world
)
2013-05-31 11:02:49.657 string[17889:303] newString = helloworld

PS:处理字母等其他元素只需将NSCharacterSet的值改变即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
+ (id)controlCharacterSet;
 
+ (id)whitespaceCharacterSet;
 
+ (id)whitespaceAndNewlineCharacterSet;
 
+ (id)decimalDigitCharacterSet;
 
+ (id)letterCharacterSet;
 
+ (id)lowercaseLetterCharacterSet;
 
+ (id)uppercaseLetterCharacterSet;
 
+ (id)nonBaseCharacterSet;
 
+ (id)alphanumericCharacterSet;
 
+ (id)decomposableCharacterSet;
 
+ (id)illegalCharacterSet;
 
+ (id)punctuationCharacterSet;
 
+ (id)capitalizedLetterCharacterSet;
 
+ (id)symbolCharacterSet;
 
+ (id)newlineCharacterSet NS_AVAILABLE(10_5, 2_0);
 
+ (id)characterSetWithRange:(NSRange)aRange;
 
+ (id)characterSetWithCharactersInString:(NSString *)aString;
 
+ (id)characterSetWithBitmapRepresentation:(NSData *)data;
 
+ (id)characterSetWithContentsOfFile:(NSString *)fName;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值