OC学习(1)-字符串

2016-06-15  本文已影响61人  deactivateuser

字符串


NSString和NSMutableString

区别

创建和初始化

常量字符串
  NSString *string =@“字符串";
  NSLog(@"address:%p ,%@", string, [string class]);
2016-06-15 14:49:50.891 OC_Assignment_3_1[1954:1279483] address=0x100001040,__NSCFConstantString,Hello world!

__NSCFConstantString是常量串,不可以修改,在内存静态存储区存储

可变字符串
   NSMutableString* cpyStr = [str mutableCopy];
   NSLog(@"cpyStr=%@,address=%p,%@", cpyStr, cpyStr,[cpyStr class]);     
2016-06-15 14:55:09.659 OC_Assignment_3_1[1978:1308744] cpyStr=Hello world!,address=0x1007001e0,__NSCFString

__NSCFString是可变串,可以修改,在内存堆区存储

字符串操作函数

NSString

  NSString* str=@“Hello world!”;
获取字符串长度
  NSLog(@"%ld",[str length]);   
获取子字符串
  NSString * ptr1 = [str substringToIndex:4];
  NSString * ptr2 = [str substringFromIndex:3]; 
2016-06-15 15:13:51.073 NSString[2040:1377297] Hell
2016-06-15 15:13:51.073 NSString[2040:1377297] lo world!
判断字符串是否以指定字符串开头
  NSString* string = @"www.zihin.com";
  BOOL ret = [string hasPrefix:@"www"];
判断字符串是否以指定的字符串结尾
  NSString * string2 = @"zihin.txt";
  BOOL ret1 = [string2 hasSuffix:@".txt"];
判断字符串是否相等
  BOOL result = [string1 isEqualToString:string2]; 
比较字符串大小
  BOOL result = [string1 compare:string2];
字符串分割
  NSString* string = @"A, B, C, D"; 
  NSArray* array = [string componentsSeparatedByString:@","]; 

NSMutableString

NSString操作函数 NSMutableString都能使用

可变字符串—增加,删除,修改
- (void)insertString:(NSString *)aStringatIndex:(NSUInteger)loc;
- (void)deleteCharactersInRange:(NSRange)range;
- (void)appendString:(NSString *)aString;

OC字符串与C的字符串转化

C的字符串转化为OC的字符串
  NSString* str = [[NSString alloc]initWithUTF8String: "hello"];
OC字符串转化为C的字符串
  NSString * str = @"hello";
  const char *p = [str UTF8String];

数字转化

NSString* str = @"123";
将数字串转化成整型数据
int a = [str intValue]; 
将数字串转化成float型
float b = [str floatValue];
将数字串转化成double型
double c =  [str doubleValue];
上一篇下一篇

猜你喜欢

热点阅读