创建一个字符串对象:
1
2
3
4
5
6
7
8
9
|
NSstring * str1 = @ "hello" ;
NSString * str = [[ NSString alloc]initWithString:@ "hello world!" ];
NSString * str_1 = [[ NSString alloc]initWithUTF8String: "hello world" ]; //把C的字符串转化为OC的字符串
int a = 123;
NSString * str_3 = [[ NSString alloc]initWithFormat:@ "a = %d %s%@" , a, "abcd" , @ "efg" ]; //用格式化字符串初始化
//可完成字符串的拼接以及完成C的字符串与OC的字符串的转化 NSString * str1 = [ NSString stringWithString:@ "hello world" ];
NSString * str2 = [ NSString stringWithUTF8String: "hello world" ];
NSString * str3 = [ NSString stringWithFormat:@ "%s" , "hello world" ];
|
字符串转化:
1
2
3
4
5
6
7
|
NSString * str = @ "hello" ;
const char *p = [str UTF8String];将OC字符串转化为C的字符串
str = @ "123" ;
int a = [str intValue]; //将数字串转化成整型数据
[str floatValue]; //将数字串转化成float型
[str doubleValue]; //将数字串转化成double型
|
常用的NSString Message(OC 的字符 :typedef unsigned short unichar)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
NSLog (@ "%ld" ,[str1 length]); //求字符串长度
NSLog (@ "%c" , [str1 characterAtIndex:1]); //获取字符串中的字符
BOOL ret = [str1 isEqualTo:str2]; //比较两个字符串是否相等,相等返回YES(1),不相等返回NO(0) (BOOL YES(1) NO(0))
long ret1 = [str1 compare:str2]; //比较两个字符串的大小,str1大于 返回1 相等返回0 小于返回-1
long ret2 = [str1 caseInsensitiveCompare:str2]; //不区分大小写比较字符串大小
NSString * ptr = [str2 uppercaseString]; //将字符串中的所有小写字符转换成大写 不改变原来的字符串
ptr = [str1 lowercaseString]; //将字符串中的所有大写字符转换成小写 不改变原来的字符串
ptr = [str3 capitalizedString]; //将字符串中出现的第一个字母转换成大写,其余字母小写
NSString * str4 = @ "hello world" ;
NSRange range = [str4 rangeOfString:@ "wr" ]; //查找子串,找不到返回NSNotFound 找到返回location和length
if (range.location != NSNotFound ) {
NSLog (@ "%ld %ld" ,range.location, range.length);
} NSString * str5 = @ "helloworld" ;
NSString * ptr1 = [str5 substringToIndex:4]; //字符串抽取 从下标0开始到4 不包括4
NSString * ptr2 = [str5 substringFromIndex:5]; //从下标5开始抽取到字符串结束 包括5
NSRange range1 = {4,3}; //结构体初始化
NSString * ptr3 = [str5 substringWithRange:range1]; //在range指定范围内抽取
NSString * ptr4 = [str5 substringWithRange: NSMakeRange (4,3)]; //NSMakeRange可以生成一个结构体
NSString * str = @ "www.1000phone.com" ;
BOOL ret = [str hasPrefix:@ "www" ]; //判断字符串是否以指定字符串开头
NSString * str1 = @ "1.txt" ;
BOOL ret1 = [str hasSuffix:@ ".txt" ]; //判断字符串是否以指定的字符串结尾
NSMutableString 可变字符串(动态增加和减少的) 继承于 NSString 可以使用 NSString 的所有方法
NSMutableString * str = [[ NSMutableString alloc]initWithString:@ "hello" ]; //将不可变的字符串转换为可变的字符串
[str insertString:@ "123" atIndex:1]; //在指定下标(不要越界)位置插入NSString类型字符串
[str appendString:@ "123" ]; //在字符串末尾追加字符串
[str deleteCharactersInRange: NSMakeRange (0, 2)]; //从指定下标删除length个字符
[str setString:@ "qianfeng" ]; //修改字符串亦称对该可变字符串赋值
[str replaceCharactersInRange: NSMakeRange (3, 1) withString:@ "ios" ]; //将指定下标位置的length个字符替换为指定的字符串
|
本文转自夏雪冬日博客园博客,原文链接:http://www.cnblogs.com/heyonggang/p/3452556.html,如需转载请自行联系原作者